【力扣】删除链表的倒数第N的节点
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
进阶:你能尝试使用一趟扫描实现吗?
示例 1:
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
对于链表类题目,对某一个特定索引的元素进行操作往往会成为增加运算时间的瓶颈,因此如何通过尽可能少的遍历次数寻找到所要操作的元素就成为关键。
比如这道题,由于我们不知道链表的长度,并且只能从头部开始遍历,假设我们不运用任何技巧,两次遍历可以解决这个问题。
第一次遍历可以得知链表的长度L,第二次遍历从头找到L-n位置的链表元素,删除即可。
两次遍历,时间复杂度为O(n), 空间复杂度O(1)。
能不能用1次遍历解决这个问题呢?这里我们运用到解决这类线性列表的数据结构题目一个高频技巧,双指针。
为了方便,我们在原有链表前面设置一个哑结点,哑结点的好处在于,因为这里我们是要删除一个结点,所以我们可以定位到被删除结点的前置结点,然后将前置结点的后续指针指向被删除结点的后续结点,则可完成删除。
我们设置两个指针,两个指针初始状态都指向哑结点,指针fast 先走n步,然后指针fast和指针slow同步往前继续遍历链表,直至fast的后续结点为空,此时指针slow到达被删除结点的前置结点
作者:belinda
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/solution/chao-ke-ai-dong-hua-jiao-ni-ru-he-shan-chu-lian-bi/
来源:力扣(LeetCode)
对于给定预先设定结构体的题目,我不太会使用预定义的结构体
1 # Definition for singly-linked list. 2 class ListNode: 3 def __init__(self, x): 4 self.val = x 5 self.next = None 6 7 class Solution: 8 def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: 9 if not head: 10 return head 11 slownode = ListNode(None) 12 slownode.next = head 13 fastnode = slownode 14 for i in range(n): 15 fastnode = fastnode.next 16 while(fastnode.next!=None): 17 slownode = slownode.next 18 fastnode = fastnode.next 19 if slownode.next == head: 20 head = head.next 21 else: 22 slownode.next = slownode.next.next 23 return head 24 25 作者:belinda 26 链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/solution/chao-ke-ai-dong-hua-jiao-ni-ru-he-shan-chu-lian-bi/ 27 来源:力扣(LeetCode)
浙公网安备 33010602011771号