Remove Duplicates from Sorted List

来源:互联网 发布:telnet 端口发送数据 编辑:程序博客网 时间:2024/05/16 09:15

我承认我链表真是一塌糊涂……

/** * 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) {        if (head == NULL || head->next == NULL)            return head;        ListNode *last = head, *p = head->next;        last->next = NULL;        while (p != NULL) {            if (p->val == last->val)                p = p->next;            else {                last->next = p;                last = p;                p = p->next;                last->next = NULL;            }        }        return head;    }};

另贴高人解法:

/** * 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 *pre,*now;        if(!head||!head->next)return head;        pre=head;        now=head->next;        while(now)        {            if(pre->val==now->val)            {                pre->next=now->next;                now=now->next;            }            else            {                pre=now;                now=now->next;            }        }        return head;    }};// blog.csdn.net/havenoidea

http://blog.csdn.net/havenoidea/article/details/12883023

http://oj.leetcode.com/problems/remove-duplicates-from-sorted-list/