LeetCode_Python(19)_删除链表的倒数第N个节点

需求

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

示例
给定一个链表: 1->2->3->4->5 n = 2
当删除了倒数第二个节点后,链表变为 1->2->3->5

说明
给定的 n 保证是有效的。

解决思路

  1. 已知n是有效的,不用对n进行判断,遍历链表添加到list中;
  2. 对list长度进行判断,返回不同的情况。

参考代码

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def romove_element(self, head, n):

        # 将链表元素添加到list中
        node_list = []
        while head:
            node_list.append(head)
            if head.next is None:
                break
            else:
                head = head.next

        # 如果元素个数为1,则返回None
        if len(node_list) == 1:
            return None

        # 如果元素个数恰好为n时,则删除node_list中第一个元素,并返回删除后的第一个元素
        elif len(node_list) == n:
            node_list.pop(0)
            return node_list[0]

        n = 0 - n 
        node_list[n - 1].next = node_list[n].next
        node_list.pop(n)
        return node_list[0]

猜你喜欢

转载自blog.csdn.net/weixin_33674976/article/details/87195594
今日推荐