【leetcode】19. 删除链表的倒数第N个节点
删除链表的倒数第N个节点
- 题目
- 代码
- 1. 获取长度
- 2. 双指针
题目
19. 删除链表的倒数第N个节点
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
示例 2:
输入:head = [1], n = 1
输出:[]
示例 3:
输入:head = [1,2], n = 1
输出:[1]
代码
1. 获取长度
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):def removeNthFromEnd(self, head, n):""":type head: Optional[ListNode]:type n: int:rtype: Optional[ListNode]"""if head is None:return Nonecur = headlenth = 0while cur:cur = cur.nextlenth += 1if lenth == n:return head.nextcur = headfor i in range(lenth-n-1):cur = cur.nextcur.next = cur.next.nextreturn head
2. 双指针
思路: 快指针先走n+1
步,等到NULL
时,慢指针到倒数第n个
的前面一个
节点
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):def removeNthFromEnd(self, head, n):""":type head: Optional[ListNode]:type n: int:rtype: Optional[ListNode]"""# 双指针dummy_head = ListNode(0, head)slow = fast = dummy_headfor i in range(n+1):fast = fast.nextwhile fast:slow = slow.nextfast = fast.nextslow.next = slow.next.nextreturn dummy_head.next