当前位置: 首页 > 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

相关文章:

  • 跑步前热身动作
  • 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] 错误票据
  • 给跑步入门的一个训练课表
  • 衡水企业网站设计报价/站外seo推广
  • 响应式网站制作/买卖链接网
  • 网站营销的流程/重庆网站seo服务
  • 门户网站建设要求/网站提交收录入口链接
  • 公司简介模板免费ppt下载/东莞seo广告宣传
  • ps海报设计教程网页/seo外包软件