| 删除链表中倒数第N个节点
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1
输出:[]
示例 3:
输入:head = [1,2], n = 1
输出:[1]
| 题解
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
"""
解题思路一:
1.找规律可得,倒数第n个元素为正数第s个元素 s = count - n +1
2.定义新的头指针,循环遍历添加到新的头指针,当start == n 时,跳过
3.返回新的头指针
解题思路二:
1.定义快慢指针 让fast指针先移动n步,然后fast 和 slow 同时后移 直道fast.next 为空
2.如果connt == n 即要删除的元素为第一个元素,可作为特殊情况处理
"""
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
# 解题思路一
cur = head
# 计算链表的长度
count = 0
while cur:
count += 1
cur = cur.next
# 倒数第n个元素为正数第s个元素 s = count - n +1
s = count - n + 1
# 定义新的指针点并且添加虚拟头节点
node = ListNode()
new_head = node
tail = node
start = 0
c = head
while c:
start += 1
if start == s:
c = c.next
continue
else:
tail.next = c
tail = c
c = c.next
tail.next = None # 因为tail指针一直指向尾节点,有可能尾节点后面是要删除的节点,索引把尾节点后面的节点断开
return new_head.next # 返回新的头指针
# 解法二
# 定义快慢指针 让fast指针先移动n步,然后fast 和 slow 同时后移 直道fast.next 为空
fast = head
slow = head
# 定义新的头指针和虚拟头节点
node = ListNode()
new_head = node
tail = node
count = 0
while fast and slow:
if count >= n:
fast = fast.next
tail.next = slow
tail = slow
slow = slow.next
else:
fast = fast.next
count += 1
# 如果connt == n 即要删除的元素为第一个元素,可作为特殊情况处理
if count == n:
return head.next
# 跳过count == n 的节点
tail.next = tail.next.next
# 返回新的头指针
return new_head.next