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

Title Description

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

analysis:

There are two ways for writing, ideas are traversing the list, and then delete the duplicate nodes

Writing 1: non-recursive, bis Finger

1) adding a dummy head node p, ease of handling

2) setting two pointers are now first and last, first node to point to the current, last and next moved to find a different value of the node the current node, first-> next = last

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
class Solution {
public:
ListNode* deleteDuplication(ListNode *pHead)
{
    // increase the virtual first node P 
    ListNode * P = new new ListNode (- . 1 );
    p->next=pHead;
    
    // First node points to the current, last move back and find a value different from the current node junction 
    ListNode First * = P;
    ListNode *last=pHead;

    while(last!=NULL&&last->next!=NULL)
    {
        if(last->val!=last->next->val)
        {
            first=last;
            last=last->next;
        }else
        {
            int x=last->val;
            while(last->next!=NULL)
            {
                if(last->val==x)
                {
                    last=last->next;
                }else
                {
                    break;
                }
            }
            if(last->val==x)
                last=NULL;
            first->next=last;
        }
    }
    return p->next;
}
};

Writing 2: recursion, thinking the same

ListNode* deleteDuplication(ListNode *pHead)
{
    IF (PHEAD == NULL || pHead-> Next == NULL) // only one node 0 or node 
        return PHEAD;
     IF (pHead-> Val pHead- ==> next-> Val) // Current node is a duplicate node 
    {
        ListNode * TEMP = pHead-> Next;
         the while (! = NULL && TEMP temp-> Val pHead- ==> Val) // skip the current node with all of the same node, to find a first current junction node different point 
            TEMP = temp-> Next;
         return deleteDuplication (TEMP); // recursion starts with a current from the first node different nodes 
    } the else // current node is not a duplicate nodes 
    {
        PHEAD -> Next = deleteDuplication (pHead-> Next); // keep the current node, the next node starts from the recursive 
        return PHEAD;
    }
}

Guess you like

Origin www.cnblogs.com/yinbiao/p/11589241.html