当前位置:网站首页>Sword finger offer 18 Delete the node of the linked list

Sword finger offer 18 Delete the node of the linked list

2022-06-11 08:55:00 Drag is me

leetcode Force button to brush questions and punch in

subject : The finger of the sword Offer 18. Delete the node of the linked list
describe : Given the head pointer of one-way linked list and the value of a node to be deleted , Define a function to delete the node .

Return the head node of the deleted linked list .

Their thinking

1、 Because the deleted node happens to be the head node , So in advance head Add a node before ; So you just have to judge head->next Is it equal to val;

Source code ##

class Solution {
    
public:
    ListNode* deleteNode(ListNode* head, int val) {
    
        ListNode *start = new ListNode(-1);
        ListNode *p = start;
        start->next = head;
        while (start) {
    
            if (start->next->val == val) {
     
                start->next = start->next->next;
                break;
            }
            start = start->next;
        }
        return p->next;
    }
};
原网站

版权声明
本文为[Drag is me]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110855011697.html