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.

Solution: 指针操作。

如果当前val和下一个val相等,则将per指针一直移到和这些val不等的位置。

如果当前val和下一个不等, 则这个val要保存。 那么 先将cur.next = per;  cur = cur.next; per = per.next; 注意还要让cur.next = null;这样才保证了不会加上些不需要的元素,同时 这个句子只能放在最后。

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode deleteDuplicates(ListNode head) {
14         // IMPORTANT: Please reset any member data you declared, as
15         // the same Solution instance will be reused for each test case.
16         ListNode header = new ListNode(-1);
17         header.next = null;
18         ListNode cur = header, per = head;
19         while(per != null){
20             if(per.next == null || per.val != per.next.val){
21                 cur.next = per;
22                 cur = cur.next;
23                 per = per.next;
24                 cur.next = null;
25             }else{
26                 int value = per.val;
27                 while(per != null && per.val == value){
28                     per = per.next;
29                 }
30             }
31         }
32         return header.next;
33     }
34 }

 

posted on 2013-11-13 07:25  Step-BY-Step  阅读(165)  评论(0编辑  收藏  举报

导航