虚拟头节点指针法实现链表删除指定值的节点

Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.

虚拟头节点指针法实现链表删除指定值的节点

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        if(head==nullptr){return nullptr;}
        //虚拟头节点,头指针
        ListNode hair(-1,head);ListNode*q = &hair;
        // 链表不为空执行循环
        while(q->next){
        	//下一个节点的值是否与要求数值相等
            if(q->next->val != val){
                q=q->next;
            }else{
            	//若不相等,先探测要删除节点后面是否还有节点
                if(q->next->next){
                	//有节点就改变指针指向
                    q->next= q->next->next;
                }else{
                	//无节点将指针置为空,避免野指针
                    q->next = nullptr;
                }
            }
        }
        //返回链表头节点,该节点可能为nullptr
        return hair.next;
    }
};
上一篇:faust从kafka消费nginx日志流分析告警


下一篇:浅谈自动化测试