[LeetCode] 203、移除链表元素

题目描述

删除链表中等于给定值 *val* 的所有节点。

输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5

解题思路

简单题,技巧是设置一个dummyHead节点,最后返回dummyHead->next

参考代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        if(head == nullptr)
            return nullptr;
        
        ListNode* dummyHead = new ListNode(0);
        dummyHead->next = head;
        ListNode* pNode = dummyHead;
        while(pNode != nullptr){
            while(pNode->next != nullptr && pNode->next->val == val){  // 这里要是while才行,避免 “[1,1] , 1” 这种情况出现错误
                ListNode* pDel = pNode->next;
                pNode->next = pNode->next->next;
                delete pDel;
                pDel = nullptr;
            }
            pNode = pNode->next;
        }
        
        return dummyHead->next;
    }
    
};
发布了390 篇原创文章 · 获赞 576 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/ft_sunshine/article/details/103945358