LeetCode 203. 移除链表元素

  • 题目:
    删除链表中等于给定值 val 的所有节点。

示例:

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

-解题思路一:

双指针法,遇到相同值的节点就删除

代码实现(C++)

ListNode* removeElements(ListNode* head, int val) {
        ListNode *pre, *p;
        if(head == nullptr)
            return head;
        if(head->next == nullptr){
            if(head->val == val)
            return nullptr; 
            else
                return head;
        }
        pre = head;
        p = head->next;
        while(p != nullptr)
        {
            if(p->val == val)
            {
                pre->next = p->next;
                p = pre->next;        //删除节点
            }
            else{
            pre = p;                   //更新节点
            p = p->next;
            }
        }
        if(head != nullptr && head-> val == val)            //判断头节点
        {
            if(head->next != nullptr)
                return head->next;
            else
                return nullptr;
        }
        return head;
       
    }

方法二:递归

代码实现(C++)

 ListNode* removeElements(ListNode* head, int val) {
        if(!head)
            return head;
        head->next = removeElements(head->next, val);
            return head->val == val? head->next: head;            //判断第一个节点
    }

猜你喜欢

转载自blog.csdn.net/xiao1guaishou/article/details/86292968