时间:2020-7-2
题目地址:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
题目难度:Medium
题目描述:
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5. 说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
思路1:两次遍历,第一次遍历拿到长度L,第二次找到L-n
代码段1:懒得写了
思路2:一次遍历,快慢指针
代码段2:通过
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: fast, slow = head, head while n: fast = fast.next n -= 1 if fast == None: return head.next while fast.next != None: fast = fast.next slow = slow.next slow.next = slow.next.next return head总结:
写着写着觉得算法题变成了智力题,脑筋急转弯呀,我的马鸭不过最近浮躁了是真的,根本沉不下来想算法,这题我应该是能想到的,哈哈哈,想了会没整出来就去看评论然后写出来的,我佛了