python_lintcode_372在O(1)時間複雜度刪除連結串列節點_174刪除連結串列中倒數第n個節點
阿新 • • 發佈:2019-01-05
372在O(1)時間複雜度刪除連結串列節點
題目
給定一個單鏈表中的一個等待被刪除的節點(非表頭或表尾)。請在在O(1)時間複雜度刪除該連結串列節點。
樣例
Linked list is 1->2->3->4, and given node 3, delete the node in place 1->2->4
標籤
思路
- 直接將節點的值為下一個節點的值,該節點的下一個節點是下一個節點的下一個節點。
程式碼
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param: node: the node in the list should be deletedt
@return: nothing
"""
def deleteNode(self, node):
# write your code here
if node.val != None:
node.val = node.next.val
node.next=node.next.next
174刪除連結串列中倒數第n個節點
題目
定一個連結串列,刪除連結串列中倒數第n個節點,返回連結串列的頭節點。
注意事項
連結串列中的節點個數大於等於n
樣例
給出連結串列1->2->3->4->5->null和 n = 2.
刪除倒數第二個節點之後,這個連結串列將變成1->2->3->5->null.
思路
程式碼
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param: head: The first node of linked list.
@param: n: An integer
@return: The head of linked list.
"""
def removeNthFromEnd(self, head, n):
# write your code here
if head is None or n==0:return head
first ,dao_n = head ,head
for i in range(n):
first = first.next
#如果first為None,則倒數第n個節點是第一個,刪除第一個即可
if first is None:
return dao_n.next
#直到first.next為None,dao_n可以刪除節點了
while first.next:
dao_n = dao_n.next
first = first.next
#刪除節點
dao_n.next = dao_n.next.next
return head