标签:remove duplicate 遍历 链表 linkedlist 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
.
思路:
大致思路就是,遍历链表找出重复元素的子列并删除重复元素子列,当然,第一个元素开始有重复元素的话比较特种,需要特殊考虑。删除子列的过程稍微有点绕,题目倒是不难理解。
代码:
public ListNode deleteDuplicates(ListNode head) { if(head==null) return head; ListNode p=head,q,t=head; boolean flag=false; if(p.next!=null&&p.val==p.next.val) { flag=true; t=head; } while (p.next!=null) { q=p; if(q.val==p.next.val) { while(p.next!=null&&q.val==p.next.val) p=p.next; t.next=p.next; if(t.next!=null) p=t.next; else break; } else { t=p; p=p.next; } } if(flag&&head!=null) head=head.next; return head; }
结果:
leetcode_82_Remove Duplicates from Sorted List II
标签:remove duplicate 遍历 链表 linkedlist sorted list ii
原文地址:http://blog.csdn.net/mnmlist/article/details/43446833