您的位置:首页 > 其它

Leetcode-Remove Duplicates from Sorted List II

2014-11-16 07:42 399 查看
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:

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head==null || head.next==null) return head;
ListNode preHead = new ListNode(-1);
preHead.next = head;
ListNode cur = head;
ListNode pre = preHead;

//NOTE:We need to be every carefull about the condition,
//because if the last node be deleted, the cur is null in the next step.
//however, if the node before the last node is deleted, the cur is the last node in the next step,
//we then need to stop also, otherwise cur.next.val is invalid.
while (cur!=null && cur.next!=null){
if (cur.val==cur.next.val){
while (cur.val==cur.next.val){
cur.next = cur.next.next;
if (cur.next==null)
break;
}
pre.next = cur.next;
cur = pre.next;
} else {
pre = cur;
cur = cur.next;
if (cur.next==null)
break;
}
}

return preHead.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: