当前位置: 首页 > news >正文

算法训练第三天

203.移除链表元素

思路:

很经典的链表算法。

代码:

# 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 removeElements(self, head, val):""":type head: Optional[ListNode]:type val: int:rtype: Optional[ListNode]"""if head is None:return headnow = ListNode(next=head)pos = nowwhile pos.next is not None:if pos.next.val == val:pos.next = pos.next.nextelse:pos = pos.nextreturn now.next

707.设计链表

思路:

这里题目说可以选择使用单链表或者双链表,设计并实现自己的链表。那我们就创建一个Node类去实现自己的链表,这里我选用的是单链表。

代码:

class Node:def __init__(self, val=0, next=None):self.val = valself.next = nextclass MyLinkedList(object):def __init__(self):self.head = Node()def get(self, index):""":type index: int:rtype: int"""pos = self.headi = 0while i <= index and pos is not None:pos = pos.nexti+=1if pos:return pos.valelse:return -1def addAtHead(self, val):""":type val: int:rtype: None"""new_node = Node(val=val, next=self.head.next)self.head.next = new_nodedef addAtTail(self, val):""":type val: int:rtype: None"""new_node = Node(val=val)pos = self.headwhile pos.next is not None:pos = pos.nextpos.next = new_nodedef addAtIndex(self, index, val):""":type index: int:type val: int:rtype: None"""new_node = Node(val=val)pos = self.headi = 0while i < index and pos.next is not None:pos = pos.nexti+=1if i==index:new_node.next = pos.nextpos.next = new_nodedef deleteAtIndex(self, index):""":type index: int:rtype: None"""pos = self.headi = 0while i < index and pos.next is not None:pos = pos.nexti+=1if pos.next:pos.next = pos.next.next

206.反转链表

思路:

我们可以新建一个头节点,指向为空,然后可以将给定链表使用头插入的方式逐个插入新的链表。

代码:

class Solution(object):def reverseList(self, head):""":type head: ListNode:rtype: ListNode"""new_head = ListNode()pos = headwhile pos is not None:tmp = pospos = pos.nexttmp.next=new_head.nextnew_head.next= tmpreturn new_head.next
http://www.dtcms.com/a/224886.html

相关文章:

  • 跑步前热身动作
  • Python应用for循环遍历寻b
  • RAGFlow从理论到实战的检索增强生成指南
  • 在win10/11下Node.js安装配置教程
  • Java 认识异常
  • 桥 接 模 式
  • 介绍一种LDPC码译码器
  • uv:现代化的 Python 包和项目管理工具
  • 解常微分方程组
  • GoogLeNet网络模型
  • 西瓜书第五章——感知机
  • 《江西棒球资讯》棒球运动发展·棒球1号位
  • 信息安全之为什么引入公钥密码
  • 5.31 专业课复习笔记 12
  • day42 简单CNN
  • 计算机组织原理第三章
  • C 语言栈实现详解:从原理到动态扩容与工程化应用(含顺序/链式对比、函数调用栈、表达式求值等)
  • AI Agent的“搜索大脑“进化史:从Google API到智能搜索生态的技术变革
  • 题海拾贝:P8598 [蓝桥杯 2013 省 AB] 错误票据
  • 给跑步入门的一个训练课表
  • Docker-搭建MySQL主从复制与双主双从
  • BLE 广播与扫描机制详解:如何让设备“被看见”?
  • 1.JS逆向简介
  • 应急响应靶机-web3-知攻善防实验室
  • Another Redis Desktop Manager 1.3.7 安装教程 - 详细步骤图解 (Windows)
  • CppCon 2014 学习:Parallelizing the Standard Algorithms Library
  • 2024 CKA模拟系统制作 | Step-By-Step | 20、题目搭建-节点维护
  • Linux之MySQL安装篇
  • 6个月Python学习计划 Day 10 - 模块与标准库入门
  • OpenHarmony标准系统-HDF框架之音频驱动开发