Leetcode 82: 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 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     public int val;
 5  *     public ListNode next;
 6  *     public ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode DeleteDuplicates(ListNode head) {
11         if (head == null) return null;
12         
13         ListNode fakeHead = new ListNode(1), priorprior = fakeHead, prior = head, cur = head.next;
14         fakeHead.next = head;
15         
16         while (cur != null)
17         {
18             if (cur.val != prior.val)
19             {
20                 cur = cur.next;
21                 prior = prior.next;
22                 priorprior = priorprior.next;
23             }
24             else
25             {
26                 while (cur != null && cur.val == prior.val)
27                 {
28                     cur = cur.next;
29                     prior = prior.next;
30                 }
31                 
32                 if (cur == null)
33                 {
34                     priorprior.next = null;
35                     break;
36                 }
37                 
38                 priorprior.next = cur;
39                 prior = cur;
40                 cur = cur.next;
41             }
42         }
43         
44         return fakeHead.next;
45     }
46 }

 

posted @ 2017-11-13 06:00  逸朵  阅读(83)  评论(0编辑  收藏  举报