[leetcode][list] Remove Duplicates from Sorted List II

来源:互联网 发布:梦想海贼王转盘数据 编辑:程序博客网 时间:2024/06/06 15:53

题目:

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) {if (NULL == head || NULL == head->next) return head;ListNode *p = head, *tail = NULL;//p指向当前节点,初始化为原链表第一个节点;tail指向新链表的最后一个节点,要初始化为NULLhead = NULL;//!!!head指向新链表的第一个节点,要初始化为NULLwhile (p != NULL){int val = p->val;if (p->next == NULL || p->next->val != val){//不是重复节点if (NULL == tail){tail = p;head = p;}else{tail->next = p;//将当前节点连入新链表tail = tail->next;//更新tail指针}p = p->next;//更新当前节点指针}else {//是重复节点while (p != NULL && p->val == val){//删除所有重复节点ListNode *tmp = p;p = p->next;delete tmp;}}}if (tail != NULL) tail->next = NULL;//!!!新链表最后一个节点的next为NULLreturn head;}};


0 0
原创粉丝点击