Leetcode 19

Question

Solution

先随便创建一个链表,将其与head链接起来。创建两个指针pre和cur,如果n>0,则n-=1,cur后移。如果n=0,则两个指针一起后移。直到cur.next=None。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 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:
ans = pre = cur = ListNode(0)
pre.next = head
while cur.next:
if n:
n -= 1
else:
pre = pre.next
cur = cur.next
pre.next = pre.next.next
return ans.next