您的位置:首页 > 其它

Remove Duplicates from Sorted List II

2014-11-26 19:09 232 查看

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
.

/**
* 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(null == head || null == head.next)        //只有1个节点或者空时,直接返回头结点
return head;
ListNode temp = new ListNode(0);
temp.next = head;
head = temp;//加一个头结点,不放内容

ListNode pre = head;
ListNode behind = head.next;
ListNode front = behind.next;

while(null != front){
if(behind.val == front.val){            //如果有相同的,删除掉
while(null != front && behind.val == front.val)
front = front.next;
if(null == front)
pre.next = null;
else{
pre.next = front;
behind = front;
front = front.next;
continue;
}
}
if(null != front){
front = front.next;
behind = behind.next;
pre = pre.next;
}
}
return head.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: