分类:LinkedList
考察知识点:LinkedList
最优解时间复杂度:**O(n) **
19. Remove Nth Node From End of List
Given a linked list, remove the n-th node from the end of list and return its head.
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.
Follow up:
Could you do this in one pass?
代码:
解法:
# 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
"""
#初始化
res=ListNode(0)
#注意这里fast和slow的作用是两个指针
fast=res
slow=res
res.next=head
#让它先走两步
for i in range(n+1):
fast=fast.next
while(fast!=None):
fast=fast.next
slow=slow.next
if slow==None:
return res.next
slow.next=slow.next.next
return res.next
讨论:
1.这道题的思路是两个指针你追我赶!然后自己想是想不到的,我还是看了视频解2333333
2.就是觉得ListNode在Python里很奇怪,然后才发现slow和fast其实是两个指针