Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
- Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5 - Example 2:
Input: 1->1->1->2->3
Output: 2->3
解法一
先迭代处理前面所有不重复的节点,一旦遇到重复的节点则进入下一个迭代
public ListNode deleteDuplicates(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode res=new ListNode(-1);
ListNode cur=res;
ListNode pre=head;
while(pre.next!=null&&pre.val!=pre.next.val)
{
cur.next=pre;
cur=cur.next;
pre=pre.next;
}
while(pre!=null&&pre.next!=null)
{
while(pre.next!=null&&pre.val==pre.next.val)
{
pre=pre.next;
}
pre=pre.next;
if(pre==null||pre.next==null||pre.val!=pre.next.val)
{
cur.next=pre;
cur=cur.next;
}
}
return res.next;
}
Runtime: 0 ms, faster than 100.00% of Java online submissions for Remove Duplicates from Sorted List II.
Memory Usage: 37.8 MB, less than 13.10% of Java online submissions for Remove Duplicates from Sorted List II.
解法二
令cur指向pre.next,循环判断cur.val是否等于cur.next.val,若等于则cur指向后一位,判断cur是否等于pre.next,若不等于,则说明cur指向的值重复出现了,因此令pre=cur.next,否则则没有重复出现,pre指向下一位
public ListNode deleteDuplicates(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode res=new ListNode(-1);
ListNode pre=res;
res.next=head;
while(pre.next!=null)
{
ListNode cur=pre.next;
while(cur.next!=null&&cur.val==cur.next.val)
cur=cur.next;
if(cur!=pre.next)
pre.next=cur.next;
else
pre=pre.next;
}
return res.next;
}
Runtime: 0 ms, faster than 100.00% of Java online submissions for Remove Duplicates from Sorted List II.
Memory Usage: 37.8 MB, less than 15.97% of Java online submissions for Remove Duplicates from Sorted List II.
解法三——递归
当head为空或者head的下一个节点为空时,返回head,如果head的值和它的下一个节点的值相等,则令head指向下一位,循环到head.val!=head.next.val时返回deleteDuplicates(head.next),即跳过当前位;如果不相等,则令head.next=deleteDuplicates(head.next),即保留当前位。最后返回处理完毕的head
public ListNode deleteDuplicates(ListNode head) {
if(head==null||head.next==null)
return head;
if(head.next!=null&&head.val==head.next.val){
while(head.next!=null&&head.val==head.next.val)
head=head.next;
return deleteDuplicates(head.next);
}
head.next=deleteDuplicates(head.next);
return head;
}
Runtime: 0 ms, faster than 100.00% of Java online submissions for Remove Duplicates from Sorted List II.
Memory Usage: 37.6 MB, less than 31.63% of Java online submissions for Remove Duplicates from Sorted List II.