其他分享
首页 > 其他分享> > leetcode: 203. Remove Linked List Elements

leetcode: 203. Remove Linked List Elements

作者:互联网

leetcode: 203. Remove Linked List Elements

原题链接
方法一:直接使用原来的链表来进行移除节点操作:

/**
 * 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 != nullptr && head->val == val) {
            ListNode* tmp = head;
            head = head->next;
            delete tmp;    
        }

        // 删除非头结点
        ListNode* cur  = head;
        while (cur != nullptr && cur->next != nullptr) {
            if (cur->next->val == val) {
                ListNode* tmp = cur->next;
                cur->next = tmp->next;
                delete tmp;
            } else {
                cur = cur->next;
            }
        }
        return 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) {
        ListNode* dummyHead = new ListNode();
        dummyHead->next = head;

        ListNode* cur = dummyHead;
        while (cur != nullptr && cur->next != nullptr) {
            if (cur->next->val == val) {
                ListNode* tmp = cur->next;
                cur->next = tmp->next;
                delete tmp;
            } else {
                cur = cur->next;
            }
        }

        head = dummyHead->next; // 这一句必须加,否则可能存在head所指的结点已经被释放的情况
        delete dummyHead;
        return head;
    }
};

标签:203,Elements,ListNode,cur,val,nullptr,List,head,next
来源: https://blog.csdn.net/weixin_43065897/article/details/121873120