来源

来源:力扣(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

题解

哨兵法

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. class Solution {
  10. public ListNode removeElements(ListNode head, int val) {
  11. ListNode sentinel = new ListNode(0);
  12. sentinel.next = head;
  13. ListNode prev = sentinel, curr = head;
  14. while (curr != null) {
  15. if (curr.val == val) {
  16. prev.next = curr.next;
  17. } else {
  18. prev = curr;
  19. }
  20. curr = curr.next;
  21. }
  22. return sentinel.next;
  23. }
  24. }

复杂度分析

  • 时间复杂度:203. 移除链表元素(Remove Linked List Elements) - 图1,只遍历了一次。
  • 空间复杂度:203. 移除链表元素(Remove Linked List Elements) - 图2