zl程序教程

您现在的位置是:首页 >  Python

当前栏目

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)