Remove Duplicates from Sorted List II
Total Accepted: 40273 Total Submissions: 160820My Submissions
Question Solution
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
.
Show Tags
分析,依次遍历链表中数据,使用两个“指针”一个标识可能重复的起始点,一个标识可能重复的终止点
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode X=new ListNode(0);
X.next=head;
ListNode p=X;
ListNode q=X;
while(p.next!=null)
{
if(p.next.next!=null)
{
if(p.next.next.val==p.next.val)
p=p.next;
else
{
if(p!=q)
{
q.next=p.next.next;
p=q;
}
else
{
q=q.next;
p=p.next;
}
}
}
else
{
if(p!=X)
{
if(p.val==p.next.val)
{
q.next=null;
p=q;
}
else
{
q=q.next;
p=p.next;
}
}
else
break;
}
}
return X.next;
}
}
时间: 2024-10-18 17:46:17