[List] LeetCode remove sorts the list of repeating elements II

Topic Description

Given a sorted list, delete all of the nodes contain repeated digits, leaving only the digital original list is not recurring.
Example:

输入: 1->2->3->3->4->4->5
输出: 1->2->5

Topic links : https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/
before doing this problem, you can do first remove sorts the list of repeating elements , problem solution .

Thinking

This is a question on the topic of "prove safety Offer". We need to save three pointers: the current node curNode, the current node before a node preNode, the next node nextNode current node. Since all of the list may be repeated element, so after deleting the list is empty, it is necessary to construct a new head point to the original node newHead head node head. First newHead assigned preNode, head assigned curNode, head-> next assigned nextNode, and determines curNode-> val and nextNode-> val is equal, if equal, to illustrate the repetitive elements found, then moved to the nextNode curNode-> first node different val, and then updates the pointer; if curNode of different nextNode val, the pointer is updated. Note that in both cases (if there are duplicate elements) different way to update pointers, see specific codes:

/**
 * 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==nullptr){
            return nullptr;
        }

        ListNode* newHead = new ListNode(0);
        newHead->next = head;
        ListNode* preNode = newHead;
        ListNode* curNode = head;
        ListNode* nextNode = curNode->next;
        while(nextNode!=nullptr){
            bool findRepeat = false;    // 是否找到重复节点
            while(curNode!=nullptr && nextNode!=nullptr && curNode->val==nextNode->val){
                nextNode = nextNode->next;
                flag = true;
            }
            if(findRepeat){ //找到重复节点
                curNode = nextNode; 
                preNode->next = curNode;
            }else{  // 没找到重复节点
                preNode = curNode;
                curNode = nextNode;
            }
            if(nextNode!=nullptr){  // 更新nextNode
                nextNode=nextNode->next;
            }
        }
        return newHead->next;
    }
};

Guess you like

Origin www.cnblogs.com/flix/p/12670568.html