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?
while rabbit.next != None:
rabbit = rabbit.next
turtle = turtle.next
應該改成 兔子偷跑 先偷跑 n 步
for _ in range(n):
rabbit = rabbit.next
#print(dummyNode)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
dummyNode = ListNode()
# DummyNode (0)
dummyNode.next = head
# DummyNode -> 1 -> 2 -> 3 -> 4 -> 5
# 0 -> 1 -> 2 -> 3 -> 4 -> 5
turtle = dummyNode
rabbit = dummyNode
for _ in range(n):
rabbit = rabbit.next
#print(dummyNode)
print(rabbit)
# rabbit's position : 3
print(rabbit.val)
while rabbit.next != None:
rabbit = rabbit.next
turtle = turtle.next
#print(dummyNode)
print(rabbit)
print(turtle)
#print('before:',dummyNode)
turtle.next = turtle.next.next # 以 ex 來看 , 修改下一步(4)為下下步(5)
#print('after:',dummyNode)
return dummyNode.next