Leetcode137: Remove Duplicates from Sorted List II

来源:互联网 发布:网络品牌续费上海勤拙 编辑:程序博客网 时间:2024/05/16 07:29

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.

/** * 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,*cur;        ListNode* temp = new ListNode(-1);        temp->next = head;        pre = temp;        cur = head;        while(cur && cur->next)        {            if(cur->val == cur->next->val)            {                while(cur->next && cur->val == cur->next->val)                {                    cur = cur->next;                }                pre->next = cur->next;                cur = cur->next;            }            else            {            pre = cur;            cur = cur->next;            }        }        return temp->next;    }};


0 0
原创粉丝点击