題目鏈接
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