[LeetCode][Java] Remove Duplicates from Sorted List II

题意:

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

题目:

给定一个有序链表,删除全部反复的节点。剩余都是原链表中的不同样的节点元素。

比方。

给定1->2->3->3->4->4->5 。返回1->2->5.

给定1->1->1->2->3 ,返回2->3.

算法分析:

设置前后双指针。后指针遇到反复元素就一直遍历直到反复的结尾,之后前指针指向后指针,这样就略过全部的反复元素。

AC代码:

<span style="font-family:Microsoft YaHei;font-size:12px;">public class Solution 
{
    public  ListNode deleteDuplicates( ListNode head) 
    {
        ListNode pre;
        ListNode cur;
        ListNode newhead = new ListNode(0);
        newhead.next=head;
        if(head==null||head.next==null)
        	return head;
        pre=newhead;
        cur=head;
        while(cur.next!=null)
        {
	        if(cur.next.val==cur.val)//处理头几个元素同样的样例 如1 1 1 2 3 4 
	        {
	        	while(cur.next.val==cur.val)
	        	{
		        	cur=cur.next;
		        	if(cur.next==null)//处理末尾几个元素同样的样例 1 2 3 4 5 5 5
		        		break;
	        	}
		        pre.next=cur.next;
		        //pre=pre.next;
		        cur=cur.next;
		        if(cur==null)
		        	break;
	        }
	        else//处理头几个元素不同样的样例 1 2 3 4 5
	        {
	        	pre=pre.next;
	        	cur=cur.next;
	        }

        }
    	return newhead.next;
    }
}</span>


posted @ 2017-05-21 19:26  llguanli  阅读(117)  评论(0编辑  收藏  举报