Leetcode——19. 删除链表的倒数第N个节点

题目描述

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

示例:

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

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

题目理解

  1. 什么是链表
    单链表

代码实现

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """

        first = second = head
        #将第一个指针移动n个位置
        for _ in range(n):
            first = first.next
        #当极端情况,first指向了最后一个节点
        #且要删除的是第一个节点(倒数第n个)
            
        if not first:
            return head.next
        #将两个指针同步后移
        #直到first指向了最后一个节点(两个指针始终保持相同间隔)
        while first.next:
            first= first.next
            second = second.next
        second.next =second.next.next
        return head

猜你喜欢

转载自blog.csdn.net/Heitao5200/article/details/84838421