LeetCode Remove Duplicates from Sorted List

class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
        if (head == NULL) return NULL;
        ListNode *pre, *cur, *tmp;
        pre = head;
        cur = head->next;
        while (cur != NULL) {
            if (pre->val == cur->val) { // dup found
                tmp = cur;
                cur = tmp->next;
                pre->next = tmp->next;
                delete tmp;
            } else {
                pre = cur;
                cur = pre->next;
            }
        }
        return head;
    }
};

水一发

第二轮:

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.

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9  // 9:54
10 class Solution {
11 public:
12     ListNode *deleteDuplicates(ListNode *head) {
13         if (head == NULL) {
14             return NULL;
15         }
16         ListNode* last = head;
17         ListNode* cur = head->next;
18         ListNode* pre = head;
19         while (cur != NULL) {
20             if (cur->val != pre->val) {
21                 last->next = cur;
22                 last = cur;
23             }
24             pre = cur;
25             cur = cur->next;
26         }
27         last->next = NULL;
28         return head;
29     }
30 };

 对比了一下原来还有delete

posted @ 2014-04-17 19:31  卖程序的小歪  阅读(127)  评论(0编辑  收藏  举报