您的位置:首页 > 编程语言 > Python开发

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

2016-06-18 16:30 555 查看

题目链接

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,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!

转载请注明:/article/11857871.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: