资讯专栏INFORMATION COLUMN

[LeetCode] Remove LinkedList Elements

sherlock221 / 223人阅读

摘要:链表基本的删除操作,最好掌握以下三种方法。

Problem

Remove all elements from a linked list of integers that have value val.

Example

Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5

Note

链表基本的删除操作,最好掌握以下三种方法。

Solution Dummy Node
public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if (head == null) return null;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy, cur = head;
        while (cur != null) {
            if (cur.val == val) pre.next = cur.next;
            else pre = pre.next;
            cur = cur.next;
        }
        return dummy.next;
    }
}
Recursion
public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if (head == null) return head;
        head.next = removeElements(head.next, val);
        return head.val == val ? head.next : head;
    }
}
Iteration
public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        while (head != null && head.val == val) head = head.next;
        ListNode cur = head;
        while (cur != null && cur.next != null) {
            if (cur.next.val == val) cur.next = cur.next.next;
            else cur = cur.next;
        }
        return head;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/64771.html

相关文章

  • LeetCode 203:移除链表元素 Remove LinkedList Elements

    摘要:删除链表中等于给定值的所有节点。链表的删除操作是直接将删除节点的前一个节点指向删除节点的后一个节点即可。这就无需考虑头节点是否为空是否为待删除节点。 删除链表中等于给定值 val 的所有节点。 Remove all elements from a linked list of integers that have value val. 示例: 输入: 1->2->6->3->4->5-...

    hzc 评论0 收藏0
  • LeetCode 203:移除链表元素 Remove LinkedList Elements

    摘要:删除链表中等于给定值的所有节点。链表的删除操作是直接将删除节点的前一个节点指向删除节点的后一个节点即可。这就无需考虑头节点是否为空是否为待删除节点。 删除链表中等于给定值 val 的所有节点。 Remove all elements from a linked list of integers that have value val. 示例: 输入: 1->2->6->3->4->5-...

    makeFoxPlay 评论0 收藏0
  • [Leetcode] Combination Sum 组合数之和

    摘要:深度优先搜索复杂度时间空间递归栈空间思路因为我们可以任意组合任意多个数,看其和是否是目标数,而且还要返回所有可能的组合,所以我们必须遍历所有可能性才能求解。这题是非常基本且典型的深度优先搜索并返回路径的题。本质上是有限深度优先搜索。 Combination Sum I Given a set of candidate numbers (C) and a target number (...

    GitCafe 评论0 收藏0
  • [Leetcode] Sliding Window Maximum 滑动窗口最大值

    摘要:这样,我们可以保证队列里的元素是从头到尾降序的,由于队列里只有窗口内的数,所以他们其实就是窗口内第一大,第二大,第三大的数。 Sliding Window Maximum Given an array nums, there is a sliding window of size k which is moving from the very left of the array to...

    lvzishen 评论0 收藏0
  • [Leetcode] Zigzag Iterator Z形迭代器

    摘要:用变量和取模来判断我们该取列表中的第几个迭代器。同样,由于每用完一个迭代器后都要移出一个,变量也要相应的更新为该迭代器下标的上一个下标。如果迭代器列表为空,说明没有下一个了。 Zigzag Iterator Given two 1d vectors, implement an iterator to return their elements alternately. For exa...

    SolomonXie 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<