LeetCode 刷题记录: 19. Remove Nth Node From End of List [Python]

原题

https://leetcode.com/problems/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.

Follow up:

Could you do this in one pass?

思路

使用两个指针fast以及slow,fast先出发,slow相隔n位再出发。当fast走到尽头时slow跳过下一指针即可。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 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:
slow=fast=self
self.next=head
while fast.next:
if n:
n-=1
else:
slow=slow.next
fast=fast.next
slow.next=slow.next.next
return self.next

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×