当前位置:网站首页>【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
边栏推荐
- Custom exception
- 让您的HMI更具优势,FET-G2LD-C核心板是个好选择
- Evaluation of embedded rz/g2l processor core board and development board of Feiling
- 【LeetCode】1162-地图分析
- MySQL -- Index Optimization -- order by
- 4. Jctree related knowledge learning
- 07_ Hash
- 【LeetCode】1020-飞地的数量
- 百变大7座,五菱佳辰产品力出众,人性化大空间,关键价格真香
- Common English abbreviations for data analysis (I)
猜你喜欢

LeetCode刷题——去除重复字母#316#Medium

MySQL calculate n-day retention rate

损失函数与正负样本分配:YOLO系列

. Net again! Happy 20th birthday

How to avoid 7 common problems in mobile and network availability testing

LeetCode刷题——奇偶链表#328#Medium

Solve the problem of frequent interruption of mobaxterm remote connection

19_Redis_宕机后手动配置主机

做好抗“疫”之路的把关人——基于RK3568的红外热成像体温检测系统

密码学基础知识
随机推荐
LeetCode刷题——奇偶链表#328#Medium
搭建自己的语义分割平台deeplabV3+
Real estate market trend outlook in 2022
Markdown tutorial
[solution] educational codeforces round 82
04_ Stack
SQL transaction
Case introduction and problem analysis of microservice
06_ Stack and queue conversion
03_ Linear table_ Linked list
Bing.com網站
08_ strand
工程师评测 | RK3568开发板上手测试
NBA player analysis
Loss function and positive and negative sample allocation: Yolo series
LeetCode_ Sliding window_ Medium_ 395. Longest substring with at least k repeated characters
Recommended configuration of tidb software and hardware environment
6.12 企业内部upp平台(Unified Process Platform)的关键一刻
Topology architecture of the minimum deployment of tidb cluster
士官类学校名录