题目地址(203. 移除链表元素)
https://leetcode-cn.com/problems/remove-linked-list-elements/
题目描述
给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。示例 1:输入:head = [1,2,6,3,4,5,6], val = 6输出:[1,2,3,4,5]示例 2:输入:head = [], val = 1输出:[]示例 3:输入:head = [7,7,7,7], val = 7输出:[]提示:列表中的节点数目在范围 [0, 104] 内1 <= Node.val <= 500 <= val <= 50
前置知识
- 链表
公司
- 暂无
思路
定义一个头结点 指向给定的节点 然后定义pre指向自己定义的头结点 cur指向后节点 也就是给定的head 当cur的val = 给定的val时 就让pre节点的next指向cur的next
cur指向cur.next 如果不等于的话就让pre = pre.next 最后返回自定义的头结点的next
Java Code:
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) {if (head == null) {return head;}ListNode touNext = new ListNode(-1, head);ListNode pre = touNext;ListNode cur = pre.next;while (cur != null) {if (cur.val == val) {pre.next = cur.next;} else {pre = cur;}cur = cur.next;}return touNext.next;}}
复杂度分析
令 n 为数组长度。
- 时间复杂度:
#card=math&code=O%28n%29&id=NMPnV)
- 空间复杂度:
