码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Remove Duplicates from Sorted List II

时间:2015-01-07 23:25:52      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

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  *     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         if (head == null || head.next == null) {
15             return head;
16         }
17         ListNode start = new ListNode(head.val - 1);
18         ListNode temp=start;
19         ListNode curr=head;
20         int prev=start.val;
21         int next=head.next.val;
22         while (curr.next != null) {
23             if (curr.val != prev && curr.val != curr.next.val) {
24                 prev = curr.val;
25                 temp.next = curr;
26                 temp=temp.next;
27                 curr = curr.next;
28             } else {
29                 prev=curr.val;
30                 curr=curr.next;
31                 if(curr.next!=null) next=curr.next.val;
32             }
33         }
34         if (curr.val != prev) {
35             temp.next = curr;
36         }else temp.next=null;
37         return start.next;
38         
39     }
40 }

 

LeetCode Remove Duplicates from Sorted List II

标签:

原文地址:http://www.cnblogs.com/birdhack/p/4209595.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!