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
题意
给定有序链表,凡有重复元素者,删光
思路
代码
1 class Solution { 2 public ListNode deleteDuplicates(ListNode head) { 3 if (head == null || head.next == null) return head; 4 5 ListNode dummy = new ListNode(-1); 6 dummy.next = head; 7 ListNode pre = dummy; 8 9 while (pre.next != null) { 10 ListNode cur = pre.next; 11 while (cur.next != null && cur.val == cur.next.val) { 12 cur = cur.next; 13 } 14 if (cur != pre.next) { 15 pre.next = cur.next; 16 } else { 17 pre = pre.next; 18 } 19 } 20 21 return dummy.next; 22 } 23 }