Given a linked list, remove the n-th node from the end of list and return its head.
给定一个单向链表,移除从链表的尾节点开始数的第n个节点并返回链表
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.
n的位置在链表中是有效位置
Solutions:
Python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
'''
这道题的思路还是很明确的,和单链表找中点一样,用双指针,两指针之间间隔n-1个元素
设立一个辅助头结点,指针p从辅助头结点开始,指针q从p的后n个节点开始,然后两个节点
一起开始向后移动,当q到达链表尾部的时候,p正好到达倒数第n个节点的前一个节点,直接
令p.next = p.next.next即可,最后返回链表
'''
dummy = ListNode(0)
dummy.next = head
p = dummy
q = head
while n:
q = q.next
n -= 1
while q:
p = p.next
q = q.next
p.next = p.next.next
return dummy.next