Leetcode——19. 刪除連結串列的倒數第N個節點
阿新 • • 發佈:2018-12-06
題目描述
給定一個連結串列,刪除連結串列的倒數第 n 個節點,並且返回連結串列的頭結點。
示例:
給定一個連結串列: 1->2->3->4->5, 和 n = 2.
當刪除了倒數第二個節點後,連結串列變為 1->2->3->5.
題目理解
- 什麼是連結串列
單鏈表
程式碼實現
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
first = second = head
#將第一個指標移動n個位置
for _ in range(n):
first = first.next
#當極端情況,first指向了最後一個節點
#且要刪除的是第一個節點(倒數第n個)
if not first:
return head.next
#將兩個指標同步後移
#直到first指向了最後一個節點(兩個指標始終保持相同間隔)
while first.next:
first= first.next
second = second.next
second.next =second.next.next
return head