Leetcode 203. Remove Linked List

作者: ShutLove | 来源:发表于2017-11-21 23:51 被阅读11次

Remove all elements from a linked list of integers that have value val.

Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5

思路:
要移除一个节点,则需要把前一个节点的next指向当前被移除节点的next,因此需要一个pre节点。
被移除的节点可能是head节点,因此需要一个指向head的节点。

public ListNode removeElements(ListNode head, int val) {
if (head == null) {
return null;
}

    ListNode root = new ListNode(0);
    root.next = head;
    ListNode pre = root;
    ListNode dummy = head;
    while (dummy != null) {
        if (dummy.val == val) {
            pre.next = dummy.next;
        } else {
            pre = pre.next;
        }
        dummy = dummy.next;
    }

    return root.next;
}

相关文章

网友评论

    本文标题:Leetcode 203. Remove Linked List

    本文链接:https://www.haomeiwen.com/subject/qrigvxtx.html