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
的确也很明显,我们的空间复杂度也是很高的,毕竟申请一个空间去存放我们链表每一个节点的地址。