6

LeetCode 第 203 号问题:移除链表元素

 3 years ago
source link: https://www.cxyxiaowu.com/6924.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
LeetCode 第 203 号问题:移除链表元素-程序员小吴
当前位置:程序员小吴 > LeetCodeAnimation > LeetCode 第 203 号问题:移除链表元素

本文首发于公众号「五分钟学算法」,是图解 LeetCode 系列文章之一。

个人网站:https://www.cxyxiaowu.com

题目来源于 LeetCode 上第 203 号问题:移除链表元素。题目难度为 Easy,目前通过率为 55.8% 。

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

示例:

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

主要考察了基本的链表遍历和设置指针的知识点。

定义一个虚拟头节点dummyHead,遍历查看原链表,遇到与给定值相同的元素,将该元素的前后两个节点连接起来,然后删除该元素即可。

tuy84.gif

// 203. Remove Linked List Elements
// https://leetcode.com/problems/remove-linked-list-elements/description/
// 使用虚拟头结点
// 时间复杂度: O(n)
// 空间复杂度: O(1)
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {

// 创建虚拟头结点
        ListNode* dummyHead = new ListNode(0);
        dummyHead->next = head;

ListNode* cur = dummyHead;
        while(cur->next != NULL){
            if(cur->next->val == val){
                ListNode* delNode = cur->next;
                cur->next = delNode->next;
                delete delNode;
            }
            else
                cur = cur->next;
        }

ListNode* retNode = dummyHead->next;
        delete dummyHead;

return retNode;
    }
};

用递归来解。

通过递归调用到链表末尾,然后回来,需要删的元素,将链表next指针指向下一个元素即可。

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        if (!head) return NULL;
        head->next = removeElements(head->next, val);
        return head->val == val ? head->next : head;
    }
};

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK