• [LeetCode] Remove Duplicates from Sorted List II


    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.

    Hide Tags
     Linked List
    Have you met this question in a real interview? 
    Yes
     
    No
     

    Discuss

     

    思路:和Remove Duplicates from Sorted List一样,双指针,head指向要插入node的前一个node,p指向当前处理的node。

    如何判断是否重复呢,判断p和p->next是否一样,若一样,则不插入,不一样就要插入,但是这里忽略了NULL的处理,如果p->next== NULL,要单独处理。。

    另外,在找到p->val == p->next->val 时,要找打下一个p,不等于之前的val。

    /**
     * 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;
                ListNode dummy(-1);
                head = &dummy;
    
                while(p)
                {   
                    if(p->next == NULL || p->val != p->next->val)
                    {   
                        head->next = p;
                        head = p;
                        p = p->next;
                        // to break old link
                        head->next = NULL;
                    }   
                    else
                    {   
                        //find the node which its value is not equla to p->val
                        // and store the node as new p;
                        p = p->next;
                        while(p)
                        {   
                            if(p->next == NULL)
                            {   
                                //should end
                                head->next = NULL;
                                p = NULL;// jump the outer loop
                                break;// jump the inner loop
                            }
    
                            if(p->val != p->next->val)
                            {
                                p = p->next;
                                break;
                            }
                            else
                                p = p->next;
                        }
                    }
    
                    #if 0
                    cout << "p->val	" << p->val << endl;
                    cout << "head->val	" << head->val << endl;
                    #endif
                }
                return dummy.next;
            }
    };
  • 相关阅读:
    sql增删改查-转载
    委托和事件 链接
    三层架构-转载
    ToList()方法
    Invoke--转载
    C# 6.0新特性---语法糖
    索引器
    HBase学习总结(1)
    教程-关于Owner和Parent的区别
    问题-在TreeView使用时,发现选中的树节点会闪烁或消失
  • 原文地址:https://www.cnblogs.com/diegodu/p/4347583.html
Copyright © 2020-2023  润新知