您的位置:首页 > 其它

leetcode 38: Remove Duplicates from Sorted List II

2013-01-16 08:21 495 查看
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.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(!head) return head;

int val = head->val;
ListNode ** pp = &head;
ListNode * cur = head;

if( cur->next == NULL || cur->next->val != cur->val  ) {
*pp = cur;
pp = &(cur->next);
}

while( (cur=cur->next) != NULL  ) {
if( cur->val != val) {
if( cur->next == NULL || cur->next->val != cur->val) {
*pp = cur;
pp = &(cur->next);
}
val = cur->val;
}
}

*pp = NULL;
return head;
}
};


/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/
public class Solution {

//{}, {1}, {111}, {1,2,2,2, 3}
//112
public ListNode deleteDuplicates(ListNode head) {
// Start typing your Java solution below
// DO NOT write main() function
if(head==null || head.next==null) return head;

ListNode dummy = new ListNode(0);
dummy.next = head;

ListNode pre = dummy;
ListNode p = head;
ListNode q = head.next;

boolean isdel = false;
while(q!=null) {
if(q.val==p.val) {
isdel = true;
} else {
if(isdel) {
pre.next = q;
isdel = false;  // when use flag. remmenber when it's effected, set it back.
} else {
pre = p;
}
}
p = q;
q = q.next;
}

if(isdel) pre.next = null;

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