Linked List Exercise [7]

This section is based on the Huawei computer test, a part of a medium question type. Due to the difficulty in solving it, I went to leetcode to check the similar question type for training.

Personally, I feel that the singly linked list can no longer stumped me, but I think too much. Seeing this problem of deleting the specified element is very clear, but I always encounter strange situations where the pointer points to null or the memory is not allocated.

So I spent a lot of time thinking about:

What to do after thinking about this question:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
   ListNode* deleteNode(ListNode*head, int val) 
{
    
    if (head->val == val)
        head= head->next;
    ListNode* pFind = head;
    while (pFind->next != NULL)
    {
        if (pFind->next->val == val&&pFind->next->next!=NULL)
        {
            ListNode* temp = pFind->next;
            pFind->next = temp->next;
            delete temp;
        }
        else if(pFind->next->val == val)
        {
            pFind ->next=NULL;
        }
        else if (pFind->next->val != val && pFind->next != NULL)
        {
            pFind = pFind->next;
        }
    }
    return head;

}
};

There are many good ways to read the solution, but I still can't understand it personally. Learn more in the future.

PS: I feel that Huawei’s internship may not be enough. The computer test is probably a big obstacle for me, woo woo woo

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324073813&siteId=291194637