python构建有序链data struct

类是一种数据类型,当我们不知道怎么定义一个数据类型的时候,那这个时候就一定要想到类充当包裹,类中不仅可以存放数据,也可以把那些方法也放进去

直接看代码和注释方便理解

# 定义节点,节点存有数据和next指针
class Node:
    def __init__(self,initdata):
        self.data = initdata
        self.next = None
    def getData(self):
        return self.data
    def getNext(self):
        return self.next
    def setData(self,newdata):
        self.data = newdata
    def setNext(self,newnext):
    	# 这里的next可是是任何的数据类型包括和自身相同属性的node
        self.next = newnext
        

# 定义有序链,该链是基于上面定义的node的数据类型
class OrderedList:
    # 当class实例化对象的时候执行初始化函数,定义头指针指向空
    def __init__(self):
        self.head = None
    def search(self,item):
        current = self.head
        found = False
        stop = False
        while current != None and not found and not stop:
            if current.getData() == item:
                found = True
            else:
                # 从头结点一直next寻找,如果链中的一个node的数值大于要找的值则stop,说明该链中不存在该item,后面的node也不可能会出现该item
                if current.getData() > item:
                    stop = True
                else:
                    # 继续移动next结点
                    current = current.getNext()
        return found
	
    def add(self,item):
        current = self.head
        previous = None
        stop = False
        while current != None and not stop:
            if current.getData() > item:
                stop = True
            else:
                previous = current
                current = current.getNext()
        # 新增一个node
        temp = Node(item)
        if previous == None:
            temp.setNext(self.head)
            self.head = temp
        else:
	        # 将该新node连如链中
            temp.setNext(current)
            previous.setNext(temp)       
            
    def isEmpty(self):
        return self.head == None

    def length(self):
        # 计算这个有序列表的长度
        current = self.head
        count = 0
        while current != None:
            count = count + 1
            current = current.getNext()

        return count
        
    # traverse 穿过,将这个有序列表的全部元素打印出来
    def traverse(self):
        current = self.head
        while current != None:
            print(current.getData())
            current = current.getNext()
            
        
mylist = OrderedList()
mylist.add(31)
mylist.add(77)
mylist.add(17)
mylist.add(93)
mylist.add(26)
mylist.add(54)

print(mylist.length())
print(mylist.search(93))
print(mylist.search(100))
mylist.traverse()

效果
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值