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
题意
给定有序链表,凡有重复元素者,删光
思路
指针cur负责边扫旧链表边查重
指针pre负责生成新链表
代码
1 class Solution { 2 public ListNode deleteDuplicates(ListNode head) { 3 if (head == null || head.next == null) return head; 4 ListNode dummy = new ListNode(-1); 5 dummy.next = head; 6 ListNode pre = dummy; 7 ListNode cur = head; 8 9 while (cur!= null) { 10 // check duplicates 11 while (cur.next != null && cur.val == cur.next.val) { 12 cur = cur.next; 13 } 14 // if cur != pre.next, it means cur moved and duplicates exist 15 if (cur != pre.next) { 16 pre.next = cur.next; 17 } else { 18 pre = pre.next; 19 } 20 cur = cur.next; 21 } 22 return dummy.next; 23 } 24 }