数据结构-链表的应用【2】

19. 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.

简单来说就是给定一个链表, 叫你删除从后往前数第N个节点,然后返回。

思路

我开始想的时候觉得这题挺简单的, 的确是, 但是还是要注意一些细节.

  • 首先遍历这个链表, 在遍历这个链表的时候, 我们用一个list去存放我们每一个节点的地址, 同时计数节点的个数
  • 遍历完后, 我们根据给定的n去list中找到n节点对应的前面节点和后面节点的地址, 然后修改指针的指向即可
    关键就是在第二步, 我们去找-n节点的前驱地址, 和后驱地址, 这里要注意, 如果 -n - 1超出list的索引范围我们就应该返回None, 同样对-n + 1节点也是的, 还有就是如果 -n - 1是None, 我们就直接返回head的next, 因为这样实际是删除了头节点,否则我们将-n-1的next指针指向-n + 1节点
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        if head is None:
            return head
        point, address, count = head, [], 0
        while point:
            address.append(point)
            count += 1
            point=point.next
        local_1, local_2 = address[-n - 1] if (-n - 1)>=-count else None , address[-n + 1] if (-n + 1) <= -1 else None
        # print(count)
        # print(local_1.val)
        # print(address)
        if local_1 is None:
            return head.next
        else:
            local_1.next = local_2
            return head
             

在这里插入图片描述
的确也很明显,我们的空间复杂度也是很高的,毕竟申请一个空间去存放我们链表每一个节点的地址。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值