IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    203. Remove Linked List Elements [easy] (Python)

    summer发表于 2016-06-18 08:52:41
    love 0

    题目链接

    https://leetcode.com/problems/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

    题目翻译

    删除单链表中值为给定的val的节点。比如:给定链表 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6 和值 val = 6 ,返回 1 –> 2 –> 3 –> 4 –> 5 。

    思路方法

    思路一

    遍历所有节点,同时保留每个节点的上一个节点,当遇到节点值是val时,删除该节点。为了方便操作,定义了一个伪头节点。

    代码

    # 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
    """

    new_head = pre = ListNode(0)
    pre.next = head
    while head:
    if head.val == val:
    pre.next = head.next
    else:
    pre = pre.next
    head = head.next
    return new_head.next

    思路二

    题目没有要求不改变节点的值,那么可以定义快慢两个指针,在快指针遍历链表的时候,将不等于val值的节点的值赋给慢指针指向的节点。

    代码

    # 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
    """

    new_head = ListNode(0)
    new_head.next = head
    slow, fast = new_head, head
    while fast:
    if fast.val != val:
    slow.next.val = fast.val
    slow = slow.next
    fast = fast.next
    slow.next = None
    return new_head.next

    说明
    上面的解法都用到了dummy node,其实可以先将从头部开始的val值得节点去除,这样就不需要额外的节点了。
    另外,这道题可以用递归来做,代码很简单但无法AC。。。不过用C语言写同样的代码可以AC,所以下面写一下算是提供思路,仅供参考吧。

    代码(递归,未AC)

    # 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
    """

    if not head:
    return head
    head.next = self.removeElements(head.next, val)
    return head if head.val != val else head.next

    PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
    转载请注明:http://blog.csdn.net/coder_orz/article/details/51706294



沪ICP备19023445号-2号
友情链接