LeetCode-19. 删除链表的倒数第 N 个结点【链表 双指针】
- 题目描述:
- 解题思路一:双指针
- 解题思路二:优化
- 解题思路三:0
题目描述:
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
示例 1:
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1
输出:[]
示例 3:
输入:head = [1,2], n = 1
输出:[1]
提示:
链表中结点的数目为 sz
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
进阶:你能尝试使用一趟扫描实现吗?
解题思路一:双指针
# 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: Optional[ListNode], n: int) -> Optional[ListNode]:dummy_head = ListNode()dummy_head.next = headcur = pre = dummy_headfor _ in range(n):cur = cur.nextwhile cur.next:cur = cur.nextpre = pre.nextpre.next = pre.next.nextreturn dummy_head.next
时间复杂度:O(n)
空间复杂度:O(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: Optional[ListNode], n: int) -> Optional[ListNode]:dummyHead = ListNode(next = head)slow, fast = dummyHead, dummyHeadwhile n > 0 and fast != None:fast = fast.nextn -= 1fast = fast.nextwhile fast != None:fast = fast.nextslow = slow.nextslow.next = slow.next.nextreturn dummyHead.next
时间复杂度:O(n)
空间复杂度:O(1)
解题思路三:0
时间复杂度:O(n)
空间复杂度:O(n)