Given a sorted list, delete all the duplicate elements, so that each element occurs only once.
Example 1:
Input: 1-> 1-> 2
Output: 1-> 2
Example 2:
Input: 1-> 1-> 2-> 3-> 3
Output: 1-> 2-> 3
1 / * 2 * list definition . 3 * {public class ListNode . 4 * int Val; . 5 * ListNode Next; . 6 * ListNode (int X) {X = Val;} . 7 *} . 8 * /
solution:
1 class Solution { 2 public ListNode deleteDuplicates(ListNode head) { 3 //去掉特殊情况 4 if (head == null || head.next == null) { 5 return head; 6 } 7 8 ListNode prev = head.next; 9 ListNode end = head; 10 11 while(prev != null) { 12 if (end.val == prev.val) { 13 end.next = prev.next; 14 prev = end.next; 15 } else { 16 prev = prev.next; 17 end = end.next; 18 } 19 } 20 21 return head; 22 } 23 }
Description: Note input original list may be empty, to a special judge. The rest is simple list deletion.
Solution Optimization: just create a temporary variable
1 public ListNode deleteDuplicates(ListNode head) { 2 ListNode current = head; 3 while (current != null && current.next != null) { 4 if (current.next.val == current.val) { 5 current.next = current.next.next; 6 } else { 7 current = current.next; 8 } 9 } 10 return head; 11 }
Optimization Solution II: removing the wild pointer
1 class Solution { 2 public ListNode deleteDuplicates(ListNode head) { 3 ListNode cur = head; 4 while(cur != null && cur.next != null){ 5 if(cur.val == cur.next.val){ 6 ListNode node = cur.next; 7 cur.next = node.next; 8 node.next = null;//清除野指针 9 }else{ 10 cur = cur.next; 11 } 12 13 } 14 return head; 15 } 16 }
Description (Personal understanding): ListNode = cur.next node; Next pointer still points to the node in the element cur.next.next garbage collection will not be recovered java