zoukankan      html  css  js  c++  java
  • 203_Removed-Linked-List-Elements

    203_Removed-Linked-List-Elements

    Description

    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
    

    Solution

    Java solution 1

    /**
     * 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) {
            while (head != null && head.val == val) {
                head = head.next;
            }
    
            if (head == null) {
                return null;
            }
    
            ListNode prev = head;
            while (prev.next != null) {
                if (prev.next.val == val) {
                    prev.next = prev.next.next;
                } else {
                    prev = prev.next;
                }
            }
    
            return head;
        }
    }
    

    Runtime: 7 ms.

    Java solution 2

    Using dummy head node.

    /**
     * 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 dummyHead = new ListNode(-1);
            dummyHead.next = head;
    
            ListNode prev = dummyHead;
            while (prev.next != null) {
                if (prev.next.val == val) {
                    prev.next = prev.next.next;
                } else {
                    prev = prev.next;
                }
            }
    
            return dummyHead.next;
        }
    }
    

    Runtime: 8 ms.

    Python solution

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        def removeElements(self, head, val):
            """
            :type head: ListNode
            :type val: int
            :rtype: ListNode
            """
            dummy_head = ListNode(-1)
            dummy_head.next = head
            
            prev = dummy_head
            while prev.next is not None:
                if prev.next.val == val:
                    prev.next = prev.next.next
                else:
                    prev = prev.next
                    
            return dummy_head.next
    

    Runtime: 88 ms. Your runtime beats 74.70 % of python3 submissions.

  • 相关阅读:
    Android ANR异常解决方案
    数据结构之斐波那契查找
    数据结构之插值查找
    数据结构之折半查找
    Android Task 任务
    java中“==”号的运用
    php中向前台js中传送一个二维数组
    array_unique和array_flip 实现去重间的区别
    js new Date() 获取时间
    手机端html5触屏事件(touch事件)
  • 原文地址:https://www.cnblogs.com/xugenpeng/p/9223028.html
Copyright © 2011-2022 走看看