Remove Duplicates from 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
.
思路一:
记录当前节点上一个判断的值,当当前节点的值与下一个节点的值不同,且与上一个判断的值不同,证明该节点是没有重复的,否则将其移除链表。
注意最后一个节点的判断。
1 public ListNode deleteDuplicates(ListNode head) { 2 if(head == null) { 3 return null; 4 } 5 ListNode dummy = new ListNode(0); 6 ListNode tail = dummy; 7 ListNode cur = head; 8 int curVal = Integer.MAX_VALUE; 9 while(cur.next != null) { 10 if(cur.val != cur.next.val && cur.val != curVal) { 11 tail.next = cur; 12 tail = tail.next; 13 } 14 curVal = cur.val;//更新比较值 15 cur = cur.next; 16 } 17 //最后一个节点的判断 18 if(cur.val != curVal) { 19 tail.next = cur; 20 tail = tail.next; 21 } 22 tail.next = null; 23 return dummy.next; 24 }
思路二:
用pre记录前一个节点,cur记录当前节点,遇到重复的额时候用cur跳过所有重复节点,再将pre的下一个指向cur。
1 public ListNode deleteDuplicatesII(ListNode head) { 2 if(head == null) { 3 return null; 4 } 5 ListNode dummy = new ListNode(0); 6 dummy.next = head; 7 ListNode pre = dummy; 8 ListNode cur = head; 9 while(cur != null && cur.next != null) { 10 if(cur.val == cur.next.val) { 11 while(cur != null && cur.val == pre.next.val) { 12 cur = cur.next; 13 } 14 pre.next = cur;//去重 15 } else { 16 cur = cur.next; 17 pre = pre.next; 18 } 19 } 20 return dummy.next; 21 }