leetcode: Remove Duplicates from Sorted List

来源:互联网 发布:有寓意的网名知乎 编辑:程序博客网 时间:2024/06/01 08:54

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.

两个指针一个pre,一个cur。cur和pre值相同,删除cur,cur变为cur->next;cur和pre值不同,都往后走一步

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


0 0
原创粉丝点击