力扣203. 移除链表元素

 

给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。

学习了解了链表的一些操作,复习了下c++的构造函数

/**
 * 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) {
        
        while(head!=NULL&&head->val==val){
            ListNode* tmp=head;
            head=head->next;
            delete tmp;
        }
        ListNode* cur=head;
        while(cur!=NULL&&cur->next!=NULL){
            if(cur->next->val==val){
                ListNode* tmp=cur->next;
                cur->next=cur->next->next;
                delete tmp;
            }
            else {
                cur=cur->next;
            }
        }
        return head;
    }
};

 

posted @ 2022-03-03 15:03  小草今天又在摸鱼吗  阅读(29)  评论(0)    收藏  举报