首页 > 代码库 > 19. Remove Nth Node From End of List Leetcode Python
19. Remove Nth Node From End of List Leetcode Python
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.
这道题目最直接的想法是先把整个list走一遍知道长度,然后再走 用总长度减去所要的点,得到位置就跳过。这样需要走两边 用一个pointer 时间复杂度为O(2n)
l另外一种思路是用两个指针 fast 和slow。 fast先走n 步,slow这时候从头开始走,当fast走到尾的时候slow就走到需要跳过的位置了。
这样只需要走一遍就可以了。
Intuitively, the first idea we have is to iteratively go through the whole list and then count the length of the list. Then we deduct the required spot from the end. The result is the length we need to go from the beginning.
say the whole length is L we want to delete n from the end. we need to go L-n from the begining.
This method will require us to go through the whole list for twice. The time complexity is O(2n) and require one pointer.
Another method will require two pointers. Fast and Slow.
1. fast go n steps from the beginning.
2. slow start from the beginning.
3. when fast goes to the end of the list slow goes to the spot we want to delete.
code is as follow:
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @return a ListNode def removeNthFromEnd(self, head, n): dummy=ListNode(0) dummy.next=head fast=dummy slow=dummy while n>0: fast=fast.next n-=1 while fast.next: fast=fast.next slow=slow.next slow.next=slow.next.next return dummy.next
19. Remove Nth Node From End of List Leetcode Python