描述
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 static ListNode deleteDuplicates2(ListNode head) { 2 if (head == null || head.next == null) 3 return head; 4 5 int t = Integer.MIN_VALUE; 6 ListNode fakehead = new ListNode(t);// 加了个头指针 7 fakehead.next = head; 8 ListNode ptr0 = fakehead; 9 ListNode ptr1 = fakehead.next; 10 ListNode ptr2 = fakehead.next.next; 11 boolean flag = false; 12 while (ptr2 != null) { 13 if (ptr1.data == ptr2.data) { 14 flag = true; 15 ptr2 = ptr2.next; 16 ptr1 = ptr1.next; 17 if (ptr2 == null) 18 ptr0.next = null; 19 } else { 20 if (flag) { 21 ptr0.next = ptr2; 22 flag = false; 23 ptr1 = ptr2; 24 ptr2 = ptr2.next; 25 } else { 26 ptr0 = ptr0.next; 27 ptr1 = ptr2; 28 ptr2 = ptr2.next; 29 } 30 } 31 } 32 return fakehead.next; 33 }