Python链表最新增删改查及倒序
2023-03-15 22:04:43 时间
Python链表最新增删改查及倒序
链表(linked list)是由一组被称为结点的数据元素组成的数据结构,每个结点都包含结点本身的信息和指向下一个结点的地址。
闲话不多说,直接上代码。
class Node():
def __init__(self,num,next=None):
self.num=num
self.next=next
class LinkList():
def __init__(self):
self.head=None
def produce(self):
wei=None
for i in range(10):
one=Node(i)
if self.head==None:
self.head=one
wei =one
else:
wei.next=one
wei=one
def dayin(self):
p=self.head
while p!=None:
print(p.num)
p=p.next
def charu(self):
wz=int(input("请输入插入位置:"))
data=int(input("请输入插入的值:"))
if wz==1:
one=Node(data)
one.next=self.head
self.head=one
else:
i=1
p=self.head
while i
看完代码。看不懂的才是真的需要的。为了方便只要代码的,讲解就放后面吧。
难理解的是倒序的问题。
原链表1->2->3->4->5
倒序后RT所示
如果头等于空 或者头的下一个为空,则已经倒完。
if self.headNone or self.head.nextNone
因为链表总是多指向下一个位置。这个不难理解
#定义一个current,current(现在的位置)
current=self.head
pre =None
nextNode =self.head.next
while nextNode!=None:
current.next=pre
pre = current
current=nextNode
nextNode=nextNode.next
current.next=pre
self.head=current
还没有看懂么,那来看下面
class Node():
def __init__(self,num,next=None):
self.num=num
self.next=next
a=Node(1)
b=Node(2)
c=Node(3)
a.next=b
b.next=c
p=a
print(p.num)
p=p.next
print(p.num)
p=p.next
print(p.num)
p=p.next
print(p)
这个很基础了
while p!=None:
print(p.num,end=' ')
p=p.next
class Node():
def __init__(self,num,next=None):
self.num=num
self.next=next
a=Node(1)
b=Node(2)
c=Node(3)
a.next=b
b.next=c
d=Node(4)
a.next.next.next=d
print(a.next.next.next.num)
print(c.next.num)
相关文章
- Python中的函数与方法 以及Bound Method和Unbound Method
- 一文贯通python文件读取
- Python 中的异步编程:Asyncio
- 7个你现在就该学习Python的理由
- 提高Python运行效率的六个窍门
- Python数据科学:神经网络
- 一篇文章看懂大数据分析就业前景及职能定位
- R和Python中的文本挖掘:8个入门小贴士
- 告诉你为什么Python有点慢,但我却无所谓?
- 专注学习DevOps编程语言Top 5推荐
- Python发送邮件脚本
- Python多进程并行编程实践: mpi4py 的使用
- Python语言在未来的发展前景
- Python vs Ruby: 谁是最好的 web 开发语言?
- Python对Ruby:谁在Web开发领域更胜一筹?
- Python一行代码完成并行任务
- Python开发者2017应该关注的七个类库
- python爬虫入门基本知识
- 在终端中优雅地编写Python
- Python机器学习实战:信用卡欺诈检测