来源
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-linked-list-elements/
描述
删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
题解
哨兵法
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/class Solution {public ListNode removeElements(ListNode head, int val) {ListNode sentinel = new ListNode(0);sentinel.next = head;ListNode prev = sentinel, curr = head;while (curr != null) {if (curr.val == val) {prev.next = curr.next;} else {prev = curr;}curr = curr.next;}return sentinel.next;}}
复杂度分析
- 时间复杂度:
,只遍历了一次。
- 空间复杂度:
