83. Remove Duplicates from Sorted List

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

其他简洁做法:

1.双while

参考自:https://discuss.leetcode.com/topic/2168/concise-solution-and-memory-freeing


class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
        ListNode* cur = head;
        while (cur) {
            while (cur->next && cur->val == cur->next->val)
                cur->next = cur->next->next;
            cur = cur->next;
        }
        return head;
    }
};

2.双指针

参考自:https://discuss.leetcode.com/topic/2168/concise-solution-and-memory-freeing

ListNode *deleteDuplicates(ListNode *head) {
    ListNode*cur=head,*tail=head;
    while(cur){
        if(cur->val!=tail->val){
            tail->next=cur;
            tail=cur;
        }
        cur=cur->next;
        tail->next=NULL;
    }
    return head;
}


2016-08-12 12:37:15