LeetCode 82. Remove Duplicates from Sorted List II(链表题目)

LeetCode 82. Remove Duplicates from Sorted List II(链表题目)

注:该题和普通的删除指定值的结点(203)还不一样,该题需要确定不重复的值,也就是真正能向后传递的值(结点),可以采用虚拟头结点dummy + 是否重复的标志flag。

题目描述:

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Example:

Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5

Example 2:
Input: 1->1->1->2->3
Output: 2->3

思路分析

采用虚拟头结点,但要注意的是重复的均要删除,要保证指向,所以这里设置一个标志,查看是否出现重复现象,分量汇总情况进行指针指向的调节。必须连续两个结点不相同的时候,才能把pre这个目标链表的指针跟着指向下一个,否则pre->next=NULL。

具体代码:

/**
 * 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* dummy=new ListNode(0);
        dummy->next=head;
        ListNode* cur=head;
        ListNode* pre=dummy;  //跟着遍历一起走             
        while(cur)
        {
            bool flag=false;
            while(cur->next&&cur->next->val==cur->val)
            {
                flag=true;
                cur=cur->next;
            }            
            if(!flag)
            {
                pre->next=cur;
                cur=cur->next;
                pre=pre->next;
            }
            else
            {
                cur=cur->next;
                pre->next=NULL;
            }            
        }      
        return dummy->next;
    }
};


猜你喜欢

转载自blog.csdn.net/qq_20110551/article/details/81428510