当前位置:网站首页>LeetCode #19.删除链表的倒数第N个结点
LeetCode #19.删除链表的倒数第N个结点
2022-07-29 05:24:00 【张楚明ZCM】
题目截图

方法一:两次遍历
第一次遍历计算链表的长度得到长度length,然后利用k=length-n取得要删除的结点处的位置。
第二次遍历,到达k位置的时候利用cur.next = cur.next.next将结点指针指向要被删除结点的后面一个。这样就成功删除了。
考虑到只有一个节点要被删除的情况,所以在头结点前还设置了一个节点ans,最后返回ans.next。
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
length, cur = 0, head
while cur:
cur = cur.next
length += 1
ans = ListNode(0,head)
cur = ans
k = length - n
while k :
cur = cur.next
k -= 1
cur.next = cur.next.next
return ans.next完整测试代码
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
length, cur = 0, head
while cur:
cur = cur.next
length += 1
ans = ListNode(0,head)
cur = ans
k = length-n
while k:
cur = cur.next
k -= 1
cur.next = cur.next.next
return ans.next
def create_linked_list(nums):
if len(nums) == 0:
return None
head = ListNode(nums[0])
cur = head
for i in range(1, len(nums)):
cur.next = ListNode(nums[i])
cur = cur.next
return head
def print_linked_list(list_node):
if list_node is None:
return
cur = list_node
while cur:
print(cur.val, '->', end=' ')
cur = cur.next
print('null')
class main():
a = Solution()
nums = [1, 2, 51, 9, 26, 72, 4, 8]
n = 3
h = create_linked_list(nums)
b= a.removeNthFromEnd(head=h,n=n)
print(nums)
print("删除倒数第{0}个结点,该结点数值为{1}".format(n, nums[len(nums)-n]))
print()
print("删除后链表的结果如下:")
print_linked_list(b)
if __name__ == '__main__':
main()方法二:栈
先将整个链表存储栈中,然后利用栈的特性,将末尾的元素出栈。再找到出栈后的栈顶元素,该结点就是被删除结点的前一个结点,使该节点指向被删除结点的后一个结点即可成功删除指定结点。
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
ans = ListNode(0,head)
stack = list()
cur = ans
while cur:
stack.append(cur)
cur = cur.next
for i in range(n):
stack.pop()
prev = stack[-1]
prev.next = prev.next.next
return ans.next方法三:双指针
利用先后两个指针遍历。无需计算链表长度。
因为要求删除链表倒数第n个结点,那么第一个指针比第二个指针提前n个结点,然后一起遍历,当第1个指针到达链表尾端时,第二个指针刚好指在倒数第n个结点上。
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
ans = ListNode(0,head)
first = head
for i in range(n):
first = first.next
second = ans
while first:
first = first.next
second = second.next
second.next = second.next.next
return ans.next边栏推荐
- clickhouse 导入CSV失败 不报错但是无数据
- 智慧充电桩系统由什么组成?
- STM32 检测信号频率
- Reading papers on false news detection (I): fake news detection using semi supervised graph revolutionary network
- FPGA based: multi-target motion detection (hand-in-hand teaching ①)
- 传统模型预测控制轨迹跟踪——波浪形轨迹(功能包已经更新)
- 【软件工程之美 - 专栏笔记】29 | 自动化测试:如何把Bug杀死在摇篮里?
- 封装——super关键字
- EPS32+Platform+Arduino 跑马灯
- markdown与Typora
猜你喜欢

给二维表添加时间序列索引

【软件工程之美 - 专栏笔记】14 | 项目管理工具:一切管理问题,都应思考能否通过工具解决

TLE5012b+STM32F103C8T6(bluepill)读取角度数据

简洁代码实现pdf转word文档

shell工具finalShell

【软件工程之美 - 专栏笔记】17 | 需求分析到底要分析什么?怎么分析?

ML10 self study notes SVM

Huawei cloud 14 days Hongmeng device development -day1 environment construction

基于51单片机的DAC0832波形发生器

Pytorch's data reading mechanism
随机推荐
QT learning notes QtSql
【软件工程之美 - 专栏笔记】20 | 如何应对让人头疼的需求变更问题?
Ml self study notes 5
给二维表添加时间序列索引
2022 spring move - core technology FPGA development post pen test question (original question and experience)
Model building in pytorch
【软件工程之美 - 专栏笔记】19 | 作为程序员,你应该有产品意识
【软件工程之美 - 专栏笔记】14 | 项目管理工具:一切管理问题,都应思考能否通过工具解决
Hal library learning notes-11 I2C
NFC双向通讯13.56MHZ非接触式阅读器芯片--Si512替代PN512
Open source based on STM32: MHD Bluetooth speaker (including source code +pcb)
低成本2.4GHz 无线收发芯片--Ci24R1
倾角传感器用于通信铁塔、高压电塔长期监测
Ml6 self study notes
IDEA安装scala
QT learning notes - Import and export of Excel
Dust and noise monitoring system
【软件工程之美 - 专栏笔记】22 | 如何为项目做好技术选型?
【软件工程之美 - 专栏笔记】17 | 需求分析到底要分析什么?怎么分析?
Hal library learning notes-10 overview of Hal library peripheral driver framework