您的位置:首页 > 其它

LeetCode2.2.5(Remove Duplicates from Sorted List II)

2015-08-29 09:48 495 查看
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.

对每一个元素,检查它的下一个元素是否与其相同,如果相同则向前滑动指针,一直找到一个不同的元素为止

public static void solution_2_2_5(Node head){
Node pre=null,h=null,p=head;
while(p!=null){
if(p.next==null||p.data!=p.next.data){
if(pre==null){
pre=p;
h=pre;
}
else{
pre.next=p;
pre=p;
}
}
else{
while(p.next!=null&&p.data==p.next.data)
p=p.next;
}
p=p.next;
}
pre.next=null;
for(Node r=h;r!=null;r=r.next)
System.out.print(r.data+" ");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: