[Offer] to prove safety of the list to delete duplicate node

Title: In a sorted linked list nodes duplicate, delete the duplicate node list, the node does not retain repeated, returns the head pointer list. For example, the list 1-> 2-> 3-> 3-> 4-> 4-> 5 is treated 1-> 2-> 5

 

A: When traversing the first node is repeated, there must be a pointer to its previous node

    Because there is no transfer function prototype come in two pointers and the head node may also be deleted, so to build a new node Head

  Boolean type flag_repeat determines whether duplicate nodes, the node is deleted if repeated, the mobile node if the pointer is not repeated

/ * 
Struct ListNode { 
    int Val; 
    struct ListNode * Next; 
    ListNode (int X): 
        Val (X), Next (NULL) { 
    } 
}; 
* / 
class Solution { 
public: 
    ListNode * deleteDuplication (ListNode * PHEAD) 
    { 
        IF ( (PHEAD == nullptr a) || (pHead-> Next == nullptr a)) 
        { 
            return PHEAD; 
        } 
        // because no two pointer passed in, and the first node may also be removed, so the node to build a new head 
        ListNode = new new ListNode Head * (0); 
        head-> Next = PHEAD; 
        
        ListNode Head * = P prev; 
        ListNode * • pNode = PHEAD; 
        the while (! • pNode = nullptr a) 
        {
            bool flag_repeat = false; // determines whether there are duplicate node 
            IF ((pNode-> Next = nullptr a) && (pNode-> Val pNode- ==> next-> Val)!) 
            { 
                flag_repeat = to true; 
            } 
       // No repeating node IF (== flag_repeat to false) { P prev = • pNode; • pNode = pNode-> Next; }
       // node duplicate the else { ListNode pDelete = * • pNode; // duplicate nodes not preserved while ((pNode-> next! nullptr a =) && (pNode-> Val pNode- ==> next-> Val)) { • pNode = pNode-> Next; // only delete the original one delete pDelete; pDelete = pNode; } pPrev->next = pNode->next; pNode = pNode->next; //删第二个 delete pDelete; pDelete = pNode; } } return Head->next; } };

  

 

 

 

Related topics:

  Programming single chain reversal function: function to achieve reversal of a single linked list, a list input, the inverted list, return the list after the flip.

  Identify a single node in the linked list, the distance from the node to the tail pointer is K: to find a way linked list of nodes, the distance from the node to the tail pointer is K. 0 penultimate node list tail pointer of the linked list. Required time complexity is O (n).

  A set of reversed every K list: given a chain, each set of node k is flipped, and returns the list after inversion. k is a positive integer that is less than or equal to the length of the list. If the total number of nodes is not an integral multiple of k, then the node will last remaining original order.

  

 

Guess you like

Origin www.cnblogs.com/xiexinbei0318/p/11419901.html