您的位置:首页 > 编程语言 > Java开发

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

2015-07-19 10:45 387 查看

题意:


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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: