题目
Given the head
of a linked list, remove the nth
node from the end of the list and return its head.
Example 1:
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Example 2:
Input: head = [1], n = 1
Output: []
Example 3:
Input: head = [1,2], n = 1
Output: [1]
Constraints:
- The number of nodes in the list is
sz
. 1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
Follow up: Could you do this in one pass?
思路
快慢指针,块指针事先步进n格,随后与慢指针一起步进,直至快指针到达链表尾部,此时使用慢指针进行删除元素的操作。注意有可能需要删掉头节点,因此最好使用一个pre_head节点指向头节点。
代码
python版本:
# 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: Optional[ListNode], n: int) -> Optional[ListNode]:
l=r=root=ListNode(0,head)
for _ in range(n):
r=r.next
while r.next:
l=l.next
r=r.next
l.next=l.next.next
return root.next