Remove Duplicates from Sorted List I & II

Title:

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->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) {
ListNode* p = head;
ListNode* pre = NULL;
while (p != NULL){
if (pre != NULL && p->val == pre->val){
pre->next = p->next;
delete p;
p = pre->next;
}
else{
pre = p;
p = p->next;
}
}
return head;
}
};

Title:

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.

class Solution{
public:
ListNode *deleteDuplicates(ListNode *head) {
if(head == NULL || head->next == NULL){
return head;
}
ListNode *p = new ListNode(-);
p->next = head;
ListNode *cur = p, *pre = head;
while(pre != NULL){
bool isDupli = false;
while(pre->next != NULL && pre->val == pre->next->val){
isDupli = true;
pre = pre->next;
}
if(isDupli){
pre = pre->next;
continue; }
cur->next = pre;
cur = cur->next;
pre = pre->next; }
cur->next = pre;
return p->next;
}
};
上一篇:Linux档案与目录管理


下一篇:ASP.NET MVC4中调用WEB API的四个方法