0203. Remove Linked List Elements

203. 移除链表元素 #

Difficulty: 简单

删除链表中等于给定值 **_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 sential = new ListNode(0);
        sential.next = head;
        ListNode prev = sential, curr = head;
        while (curr != null) {
            if (curr.val == val) {
                prev.next = curr.next;
            } else {
                prev = curr;
            }
            curr = curr.next;
        }
        return sential.next;
    }
}

复杂度分析 #

  • 时间复杂度:O(N)。

  • 空间复杂度:O(1)。

Calendar Dec 4, 2020
Edit Edit this page
本站总访问量:  次 您是本站第  位访问者