当前位置:网站首页>【LeetCode】19-删除链表的倒数第N个结点
【LeetCode】19-删除链表的倒数第N个结点
2022-07-02 12:09:00 【酥酥~】
给你一个链表,删除链表的倒数第 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(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def removeNthFromEnd(self, head, n):
arr = []
length = 0
new = ListNode(0,head)#构造一个带头结点的链表
tmp = new
while tmp:
arr.append(tmp)
tmp = tmp.next
length += 1
arr[length-n-1].next = arr[length-n-1].next.next
return new.next
#入栈
# 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):
arr = []
new = ListNode(0,head)
tmp = new
while tmp:
arr.append(tmp)
tmp = tmp.next
for i in range(n):
arr.pop()
pre = arr.pop()
pre.next = pre.next.next
return new.next
#双指针。进阶:一趟扫描
# 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):
new = ListNode(0,head)
first = new
second = head#即new.next
for i in range(n):
second = second.next
while second:
first = first.next
second = second.next
first.next = first.next.next
return new.next
边栏推荐
- 搭建自己的语义分割平台deeplabV3+
- 06_ Stack and queue conversion
- 02. After containerization, you must face golang
- 03_线性表_链表
- 自定义异常
- Application and practice of Jenkins pipeline
- Leetcode skimming -- verifying the preorder serialization of binary tree # 331 # medium
- 【LeetCode】876-链表的中间结点
- Pytoch saves tensor to Mat file
- Solution of Queen n problem
猜你喜欢
随机推荐
Application and practice of Jenkins pipeline
Leetcode skimming -- verifying the preorder serialization of binary tree # 331 # medium
Markdown tutorial
Data analysis thinking analysis methods and business knowledge - business indicators
【网络安全】网络资产收集
LeetCode刷题——奇偶链表#328#Medium
Tidb cross data center deployment topology
Let your HMI have more advantages. Fet-g2ld-c core board is a good choice
02. After containerization, you must face golang
MD5 encryption
20_ Redis_ Sentinel mode
飞凌嵌入式RZ/G2L处理器核心板及开发板上手评测
Leetcode skimming -- count the number of numbers with different numbers 357 medium
03.golang初步使用
高考录取分数线爬虫
YOLOV5 代码复现以及搭载服务器运行
【LeetCode】1162-地图分析
15_ Redis_ Redis. Conf detailed explanation
Download blender on Alibaba cloud image station
Case introduction and problem analysis of microservice