当前位置:网站首页>【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
边栏推荐
- 10_ Redis_ geospatial_ command
- Beijing rental data analysis
- Steps for Navicat to create a new database
- 【LeetCode】1020-飞地的数量
- 19_ Redis_ Manually configure the host after downtime
- Application and practice of Jenkins pipeline
- Set set you don't know
- 20_Redis_哨兵模式
- How to intercept the value of a key from the JSON string returned by wechat?
- Markdown tutorial
猜你喜欢

Solve the problem of frequent interruption of mobaxterm remote connection

怎样从微信返回的json字符串中截取某个key的值?

2022 college students in Liaoning Province mathematical modeling a, B, C questions (related papers and model program code online disk download)

21_Redis_浅析Redis缓存穿透和雪崩

. Net again! Happy 20th birthday

04_ 栈

Redux——详解

yolo格式数据集处理(xml转txt)

Evaluation of embedded rz/g2l processor core board and development board of Feiling

Map introduction
随机推荐
【LeetCode】577-反转字符串中的单词 III
Force deduction solution summary 2029 stone game IX
18_Redis_Redis主从复制&&集群搭建
Loss function and positive and negative sample allocation: Yolo series
你不知道的Set集合
Tidb cross data center deployment topology
Application of CDN in game field
飞凌嵌入式RZ/G2L处理器核心板及开发板上手评测
Tidb data migration tool overview
Libcurl Lesson 13 static library introduces OpenSSL compilation dependency
15_ Redis_ Redis. Conf detailed explanation
Tidb data migration scenario overview
12_ Redis_ Bitmap_ command
07_ Hash
密码学基础知识
MD5 encryption
高考录取分数线爬虫
Kibana basic operation
Beijing rental data analysis
彻底弄懂浏览器强缓存和协商缓存