Leetcode刷题记录 19、删除链表的倒数第N个节点

给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。

示例:给定一个链表: 1->2->3->4->5, 和 n = 2.

当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:

给定的 n 保证是有效的。

进阶:

你能尝试使用一趟扫描实现吗?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list
思路:设置两个指针front,follow,找第n个指针就先让front往前走n步,这样front就比follow多n步,再用循环让front到达链表的末端,此时慢n步的follow就是我们要求的倒数第n个指针。

# 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:
        listl=ListNode(0)
        listl.next=head
        front=listl
        follow=listl
        for i in range(n):
            if(front.next):front=front.next
            else:return listl.next
        while front.next  is not None:
            front=front.next
            follow=follow.next
        follow.next=follow.next.next
        return listl.next
 

 

你可能感兴趣的:(写过的小程序)