• Leetcode Remove Linked List Elements


    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


    解题思路:

    方法一:

    使用“哑节点”记录链表头部。

    需要使用一个变量cur记录当前节点。

    The key to solve this problem is using a helper node to track the head of the list.

    方法二:

    使用递归recursion


    Java code:

    Method1

    //The key to solve this problem is using a helper node to track the head of the list.
        public ListNode removeElements(ListNode head, int val) {
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            ListNode cur = dummy;
            while(cur!=null && cur.next!= null) {
                if(cur.next.val == val) {
                    cur.next = cur.next.next;
                }else {
                    cur = cur.next; 
                }
            }
            return dummy.next;
     
        }

    Method2

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

    Reference:

    1. http://bookshadow.com/weblog/2015/04/24/leetcode-remove-linked-list-elements/

    2. http://www.programcreek.com/2014/04/leetcode-remove-linked-list-elements-java/

  • 相关阅读:
    实验五
    实验四
    实验三
    实验二
    寄存器(内存访问)
    实验一
    寄存器
    Mermaid 绘图总结
    电脑查看系统版本
    _ZNote_Chrom_插件_Chrom运行Android软件_APK
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4796659.html
Copyright © 2020-2023  润新知