python学习2-数据结构与算法-链表

单链表是一种链式存取的数据结构,用一组地址任意的存储单元存放线性表中的数据元素。链表中的数据是以结点来表示的,每个结点的构成:元素(数据元素的映象) + 指针(指示后继元素存储位置),元素就是存储数据的存储单元,指针就是连接每个结点的地址数据。

链表分类:

1.单向或双向

2.带头和不带头

3.循环或非循环

单链表的定义

class ListNode(object):

def init(self, val=0, next=None):

self.val = val

self.next = next

class NodeList(object):

def init(self):

self.head = Node()

def getLen(self):

if !self.head:

return 0

num = 1

while !cur.next:

num += 1

cur = cur.next

return num

#打印链表

def printList(self):

if !self.head:

print("none")

ans = []

cur = self.head

while !cur:

ans.append(curl.val)

cur = cur.next

return ans

#指定位置后面插入

def insert(self,value,index=-1):

#如果链表为空,插入第一个元素

if !self.head:

self.head = Node(value)

if index!=-1 or index!=0:

return False

return True

#若指定插入位置为第一位

if index == 0:

cur = Node(value)

cur.next = self.head

self.head = cur

return True

#若指定位置为链表尾

elif index == -1:

cur = self.head

while cur.next:

cur = cur.next

cur.next = Node(value)

else:

#index从0开始,到index-1的位置,需要移动index-1次

i = index -1

cur = self.head

while i>0 and !cur.next:

i -= 1

cur = cur.next

if !cur.next and i == 0:

tmp = cur.next

cur.next = Node(value)

cur = cur.next

cur.next = tmp

#插入位置为链表尾

elif i == 0 and !cur.next:

cur.next = Node(value)

else:

return "insert index is too large"

return self.head

#指定位置后面删除

def pop(self,value,index=-1):

if !self.head:

return False

elif !self.head.next:

if self.head.val != value:

return False

else:

self.head = None

return True

else:

cur ,pre = self.head,None

while cur:

if cur.val == value:

if cur == self.head:

self.head = cur.next

else:

pre.next = cur.next

break

else:

pre ,cur = cur,cur.next

return True

Leetcode刷题

反转整个链表(面试高频考点)-- 力扣(LeetCode)206

回文链表(数组反转ans[::-1]). - 力扣(LeetCode)234

环形链表(快慢指针). - 力扣(LeetCode)141、142

链表排序148

合并K个升序链表. - 力扣(LeetCode)23

链表每K个节点翻转. - 力扣(LeetCode)24. - 力扣(LeetCode)25

深拷贝. - 力扣(LeetCode)138

移除链表元素. - 力扣(LeetCode)19

相关推荐
西柚小萌新1 小时前
【Python爬虫基础篇】--4.Selenium入门详细教程
爬虫·python·selenium
橘猫云计算机设计1 小时前
springboot基于hadoop的酷狗音乐爬虫大数据分析可视化系统(源码+lw+部署文档+讲解),源码可白嫖!
数据库·hadoop·spring boot·爬虫·python·数据分析·毕业设计
YOULANSHENGMENG1 小时前
linux 下python 调用c++的动态库的方法
c++·python
SsummerC2 小时前
【leetcode100】零钱兑换Ⅱ
数据结构·python·算法·leetcode·动态规划
一眼青苔2 小时前
切割PDF使用python,库PyPDF2
服务器·python·pdf
电子云与长程纠缠2 小时前
Unreal Niagara制作SubUV贴图翻页动画
学习·ue5·编辑器·贴图·niagara
电商数据girl2 小时前
产品经理对于电商接口的梳理||电商接口文档梳理与接入
大数据·数据库·python·自动化·产品经理
三道杠卷胡3 小时前
【AI News | 20250424】每日AI进展
人工智能·pytorch·python·语言模型·github
xing_x_xx3 小时前
Linux系统学习----概述与目录结构
学习
DKPT3 小时前
常见正则表达式整理与Java使用正则表达式的例子
java·笔记·学习·面试·正则表达式