標籤:

[leetcode algorithms]題目19

19. Remove Nth Node From End of List

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.

自己寫的代碼:

用空間換時間,把node都放到列表裡,方便刪除鏈表元素,再把斷開的鏈表連接。運行時間75 ms

class Solution: def removeNthFromEnd(self, head, n): nodes = [] node = head while node: nodes.append(node) node = node.next if n == len(nodes): head = head.next else: nodes[-(n+1)].next = nodes[-n].next return head

推薦閱讀:

leetcode也開始收費了,大家怎麼看?
Leetcode-Maximum Subarray
Leetcode-38-Count-and-Say(學渣的痛大神們不懂。。。)
leetcode-1
leetcode-2

TAG:LeetCode |