1. 程式人生 > >[LeetCode] 19. Remove Nth Node From End of List 刪除連結串列的倒數第N個節點 @python

[LeetCode] 19. Remove Nth Node From End of List 刪除連結串列的倒數第N個節點 @python

Description

Given a linked list, remove the nth node from the end of list and return its head.

For example,

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.

給定一個連結串列,刪除連結串列的倒數第 n 個節點並返回頭結點。

例如,

給定一個連結串列: 1->2->3->4->5, 並且 n = 2.

當刪除了倒數第二個節點後連結串列變成了 1->2->3->5.

說明:

給的 n 始終是有效的。

嘗試一次遍歷實現。

Solution

構建雙指標p1p2p1先走n步,然後一同運動,當p1指向表尾,p2指向的next即是倒數第N個節點,刪除即可。


# -*- coding: utf-8 -*-
"""
Created on Sat Mar 17 16:35:29 2018

@author: Saul
"""
# 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 """ dummy = ListNode(0
) dummy.next = head p1 = p2 = dummy for i in range(n): p1 = p1.next while p1.next: p1 = p1.next p2 = p2.next p2.next = p2.next.next return dummy.next