Remove Linked List Elements-LeetCode#203

203. Remove Linked List Elements

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

Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5

移除链表中的元素
从链表中移除与 val 相等的节点
递归方法:

public class RemoveLinkedListElements {
    public ListNode removeElements(ListNode head, int val) {
        return dfs(head, val);
    }
    public ListNode dfs(ListNode head, int val) {
        if (head == null) return null;
        if (head.next != null && head.next.val == val) {
            head.next = head.next.next;
            dfs(head, val);
        } else {
            dfs(head.next, val);
        }
        return (head.val == val) ? head.next : head;
    }
}

非递归方法:

public class RemoveLinkedListElements {
    public ListNode removeElements(ListNode head, int val) {
        ListNode headListNode = new ListNode(0);
        headListNode.next = head;
        ListNode tempListNode = headListNode;
        while (tempListNode.next != null) {
            if (tempListNode.next.val == val) {
                tempListNode.next = tempListNode.next.next;
            }else {
                tempListNode = tempListNode.next;
            }
        }
        return headListNode.next;
    }
}
文章已创建 112

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部