美文网首页
Remove Linked List Elements去除链列元

Remove Linked List Elements去除链列元

作者: 穿越那片海 | 来源:发表于2017-03-16 21:58 被阅读0次

Easy

去除链列中值为val的元素

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

Definition for singly-linked list.

class ListNode(object):

def init(self, x):

self.val = x

self.next = None

我写了下面的递归代码,但是出现了running time error,说是递归深度太大。但是我看论坛里排第一的用的是相同的思路,不过是用java写得。这里不是很明白原因。

class Solution(object):
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        if not head:
            return None
        head.next = self.removeElements(head.next, val)
        return head.next if head.val == val else head

下面是另外一位coder的解法。利用指针操作。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        dummy = ListNode(-1)
        dummy.next = head
        curr = dummy
        while curr.next:
            if curr.next.val == val:
                curr.next = curr.next.next
            else:
                curr = curr.next
        return dummy.next

相关文章

网友评论

      本文标题:Remove Linked List Elements去除链列元

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