LeetCode 刷题 数据结构 链表 203 移除链表元素

Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.

Example 1:

Input: head = [1,2,6,3,4,5,6], val = 6
Output: [1,2,3,4,5]

Example 2:

Input: head = [], val = 1
Output: []

Example 3:

Input: head = [7,7,7,7], val = 7
Output: []

Constraints:

  • The number of nodes in the list is in the range [0, 104].
  • 1 <= Node.val <= 50
  • 0 <= val <= 50

今天leetcode的中文官网比较卡,所以是登录官网进行刷题的

移除链表元素这道题很简单,就是简单的对链表进行遍历,然后移除node.val = val的节点。

移除元素需要记录当前节点的前一个元素,然后直接将前一个元素的指针指向后一个元素就可以了,操作非常简单。为了保持链表中节点操作的一致,这里给head节点前增加了一个哑节点,后续的移除操作都可以使用pre.next = head.next;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        // 简单思路:直接遍历链表,移除node.val =val的节点
        ListNode pre = new ListNode(-1);
        pre.next = head;
        ListNode start = pre;
        ListNode next =null;
        while(head != null) {
            next = head.next;
            if (head.val == val) {
                pre.next = head.next;
                head.next =null;
            }else {
                pre = pre.next;
            }
            head = next;
        }
        return start.next;
    }
}

时间复杂度O(n)

空间复杂度O(1)

参考 哔哩哔哩 up主 爱学习的饲养员 刷题视频

手把手带你刷Leetcode力扣|各个击破数据结构和算法|大厂面试必备技能【已完结】-leetcode 203 移除链表元素 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值