python中基本数据结构(三)

  链表是一种非连续性的数据结构,数据元素的逻辑顺序是按照链表的指针实现,所以链表由一系列的节点组成。每个结点包括两个部分:一个是存储数据元素的数据域,另一个是存储下一个结点地址的指针域。

  

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+1)
            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:#如果插入的位置是1
            one=Node(data)
            one.next=self.head
            self.head=one
        else:
            i=1
            p=self.head
            while i<wz-1 and p!=None:#查找 要插入位置的前一个元素
                p=p.next
                i+=1
            if p==None:#如果链表长度没有要插入的位置
                print("位置异常")
            else:
                one=Node(data)
                one.next=p.next #先将此节点,链接到下一个节点
                p.next=one #在将此节点链接到前一节点的后面
    def shanchu(self):
        if self.head==None:
            print("别删除了,空空如也")
        else:
            wz=int(input("请输入要删除的位置"))
            if wz==1:#删除的如果是头结点
                print("您删除的是第一个节点,内容是",self.head.num)
                self.head=self.head.next
            else:
                i=1
                p=self.head
                while i<wz-1 and p!=None:#查找删除元素的前一个位置
                    i+=1
                    p=p.next
                if p==None or p.next==None:#如果当前节点是空或者下一个节点也就是要删除节点是空。
                    print("位置有误")
                else:
                    print("删除的内容是",p.next.num)
                    p.next=p.next.next
    def reverse(self):#链表翻转
        if self.head==None or self.head.next==None:
            print("不用到了")
        else:
            current=self.head #前驱节点
            pre    = None#当前节点
            nextNode   = self.head.next#下一个节点
            while nextNode !=None  :#当前节点为尾节点的时候循环退出,此时nextnode为空
                current.next=pre#当前节点连接到前节点
                pre     = current#前一个节点后移
                current =nextNode#当前节点后移
                nextNode = nextNode.next#下一个节点后移
            current.next = pre#最后一个节点翻转
            self.head=current
lb=LinkList()
lb.produce()
while True:
    bh=int(input("请输入编号:"))
    if bh==1: #链表插入
        lb.charu()
    elif bh==2:#链表删除
        lb.shanchu()
    elif bh==3:#链表打印
        lb.dayin()
    elif bh==4:
        lb.reverse()
    else:
        break

 

posted @ 2020-03-24 15:50  momingQI  阅读(198)  评论(0)    收藏  举报