• Python的数据结构链表


    class Node():  # 定义一个空的节点,一个是数据一个是链条指向
    def __init__(self, item):
    self.item = item # 数据是用户给予的
    self.next = None # 第一个节点的指向是空


    class Link():
    def __init__(self):
    self.head = None # 链表的数据不管是什么时候都需要一个头部,只有一个数据的时候自己就是链条头

    def add(self, item): # 链表里增加数据
    node = Node(item) # 首先创建一个节点,并在节点里传入数据 第二次传入参数生成新节点
    node.next = self.head # 链条指向头部,第一个节点next指向是空 ,第二次传入参数时 next指向了第一个节点
    self.head = node # 把node节点头数据指向第一个节点 第二次欻如参数时 节点的头部就成为了第二个节点 依次类推

    def addend(self, item):
    node = Node(item) # 先生成这个节点
    if self.isempty(): # 如果是空的话让节点头直接指向这个节点
    self.head = node
    else:
    cur = self.head # 如果不是 我们用遍历到最后一个节点
    it = None
    while cur != None:
    it = cur
    cur = cur.next
    it.next = node # 最后一个节点就是it,让这个节点的next指向生成的节点

    def bianli(self):
    rec = self.head # 遍历时 我们只需要判断头是不空就可以判断循环次数
    while rec != None: # 如果节点数据不为空我们就让它一直循环取出
    print(rec.item) # 打印出数据的值
    rec = rec.next # 第一次取出的头以后,我们让下一个节点变为头,直到这个头空了

    def remove(self, item):
    if self.head.item == item:
    self.head = self.head.next
    else:
    x = self.head
    y = None
    while x != None:
    y = x # 这样写在循环里会少一个head的判断,我们单独做一个条件判断也就是第一个if
    x = x.next # 遍历这个节点,当这个节点的值匹配上之后跳出循环,
    if x.item == item:
    break

    y.next = x.next # 这里的y相当于一直是x的上一个节点

    def inset(self, od, item):
    node = Node(item)
    if od == 0: # 如果链表位空的话。直接让把head指向生成的节点
    self.head = node
    else:
    x = self.head
    y = None
    for i in range(od - 1): # 遍历我们指定的次数,利用我们给定的位置来遍历当前节点指向
    y = x
    x = x.next
    y.next = node # 让x的上一个节点y的next指向生成的节点
    node.next = x # 让生成的节点next指向x

    def isempty(self):
    return self.head == None

    def leng(self):
    i = 0
    rec = self.head
    while rec != None:
    i += 1
    # print(rec.item)
    rec = rec.next
    return i

    def find(self, item):
    x = self.head
    y = None
    isfind = False
    while x != None:
    y = x
    if y.item == item:
    isfind = True
    break
    x = x.next
    return isfind

    def paixu(self):
    y = None
    x=self.head
    next_node=x.next
    while x != None:
    x.next=y
    y=x
    x=next_node
    if x !=None:
    next_node=next_node.next
    self.head=y
  • 相关阅读:
    把sqlserver2000的备份文件恢复到sqlserver2008中
    application、static、Session、ViewState 的区别
    命令行安装卸载服务(安装卸载.net写的服务)
    C# Windows服务自动安装与注册
    C# System.Guid.NewGuid()
    <base target="_self"/>
    C#写的windows服务,在启动时提示“服务启动后又停止了,一些服务自动停止”
    MVC中validateRequest="false"不起作用
    PL/SQL导出insert语句
    MO和MT
  • 原文地址:https://www.cnblogs.com/Centwei/p/15818290.html
Copyright © 2020-2023  润新知