python 实现链表、堆栈、队列

目录:

一、实现单链表

二、通过链表实现堆栈

三、通过链表实现队列

一、实现链表:

class Node():
    """结点类"""
    def __init__(self, data):
        self.data = data
        self.next = None
class LinkList():
    """链表类"""
    def __init__(self,node = None):
        self.__head = node
    def head(self):
        """返回链表头结点"""
        return self.__head
    def length(self):
        """返回链表的结点数"""
        count = 0
        cur = self.__head
        while cur != None:
            count += 1
            cur = cur.next
        return count
    def add(self,item):
        """在链表头添加结点"""
        node = Node(item)
        node.next = self.__head
        self.__head = node
    def travel(self):
        """遍历链表中每个结点的值"""
        cur = self.__head
        while cur !=None:
            print(cur.data)
            cur = cur.next
            
    def append(self, item):
        """在链表末尾添加结点"""
        node = Node(item)
        if self.__head==None:
            self.__head = node
        cur  = self.__head
        while cur.next != None:
            cur = cur.next
        cur.next = node
    def reverse(self):
        """链表反转"""
        cur = self.__head
        q = None
        while cur!= None:
            a = q
            q = cur
            cur = cur.next
            q.next = a
        self.__head = q
    def insert(self,pos,item):
        """在链表指定位置插入结点"""
        if pos <= 0:
            self.add(item)
        elif pos > self.length()-1:
            self.append(item)
        else:
            node = Node(item)
            cur = self.__head
            count = 0
            while count < pos-1:
                count += 1
                cur = cur.next
            node.next = cur.next
            cur.next = node
        
    def insert_linklist(self,pos,linklist):
        """在链表指定位置插入另一个链表"""
        head_2 = linklist.head()
        cur2 = head_2
        while cur2.next != None:
            cur2 = cur2.next
        cur1 = self.__head
        count = 0
        if pos <= 0:
            cur2.next = self.__head
            self.__head = head_2
            return
        while count < pos - 1 and cur1.next !=None:
            count += 1
            cur1 = cur1.next
        cur2.next = cur1.next
        cur1.next = head_2
    def remove(self,pos):
        """删除指定位置结点"""
        cur = self.__head
        if pos <= 0:
            cur = cur.next
            self.__head = cur
        else:
            count = 0
            while count < pos - 1:
                count += 1
                cur = cur.next
            remove = cur.next 
            cur.next = remove.next
        print("删除的结点位置为:%s\t数据为:%d"%(pos,remove.data))
        remove.next =None
        return remove

测试运行:

# 定义一个链表
ll = LinkList(Node(1))
ll.add(2)
ll.add(3)
ll.append(4)
ll.insert(4,5) 
ll.travel()

# 定义另一个链表
ll_ = LinkList(Node(11))
ll_.add(22)
ll_.append(33)

# 将第二个链表按照指定位置插入到第一个链表中
print('*'*100)
print("插入新链表\t")
ll_.travel()
ll.insert_linklist(8,ll_) # 链表中插入链表(22,11,33)
print('*'*100)
ll.travel()

# 对链表进行反转
print('*'*100)
print("反转")
ll.reverse() # 反转
print('*'*100)
ll.travel() # 输出反转后的链表

# 删除链表中指定位置的结点
print("*"*100)
a = ll.remove(6)
print("*"*100)
ll.travel()

运行结果:

二、通过链表实现堆栈:

堆栈特点:后进先出,因此只需按照在链表头部添加数据的方式,然后每次输出时取头结点即可。

class Node():
    """结点类"""
    def __init__(self,data):
        self.data = data
        self.next = None
        
class stack():
    """堆栈"""
    def __init__(self,):
        self.top = None
        
    def is_empty(self):
        return self.top == None
    
    def push(self, data):
        """添加数据"""
        node = Node(data)
        # 在头部插入新结点
        node.next = self.top 
        self.top = node
    
    def pop(self):
        """输出一个数据"""
        print(self.top.data)
        self.top = self.top.next
        
    def pop_all(self):
        """连续输出所有数据"""
        while self.top !=None:
            self.pop()

运行测试:

stack_A = stack()
select = 1
print("输入新结点选择:1\n堆栈中弹出一个数据:2\n结束输入选择:0")
print('*'*100)
while select != 0:
    try:
        select = int(input("选择(0/1/2):"))
    except:
        print("输入错误,请重新输入\n{0}".format('*'*100))
        continue
    if select == 1:
        stack_A.push(input("输入新结点数据:"))
        print('*'*100)
    elif select == 2:
        if stack_A.is_empty():
            print("堆栈无数据可输出\n%s"%('*'*100))
            continue
        print("弹出的数据为:")
        stack_A.pop()
        print('*'*100)
    elif select ==0:
        select = 0
        break
    else:
        print("输入错误,请重新输入\n{}".format('*'*100))
print("连续输出:")       
stack_A.pop_all()

运行结果:

三、通过链表实现队列:

队列特点为:先进先出,所以只需按照在链表尾部添加数据的方式,然后每次输出取出头结点即可。

这里指定了两个指针分别指向开头与结尾,作用是每次加入数据后更新结尾指针,再次加入数据只需在结尾指针后加入,就不需要每次加入数据时需要遍历整个单链表。

class Node():
    """结点类"""
    def __init__(self,data):
        self.data = data
        self.next = None

class queue():
    def __init__(self):
        # 定义分别指向开头与结尾的指针
        self.fore = None
        self.end = None
        
    def is_empty(self):
        return self.fore == None
    
    def in_queue(self,data):
        """队列输入数据"""
        node = Node(data)
        if self.end == None:
            self.fore = node
            self.end = node
        else:
            self.end.next = node
            self.end = node
            
    def out_queue(self):
        """队列输出数据"""
        if self.is_empty():
            print("无数据可输出")
            return
        print(self.fore.data)
        self.fore = self.fore.next
        # 如果队列无数据,初始化end
        if self.fore == None:
            self.end = None
            
    def out_all(self):
        """队列输出全部数据"""
        while self.fore != None:
            self.out_queue()

运行测试:

q = queue()
select = 1
print("输入新结点选择:1\n队列中弹出一个数据:2\n结束输入选择:0")
print('*'*100)
while select != 0:
    try:
        select = int(input("选择(0/1/2):"))
    except:
        print("输入错误,请重新输入\n{0}".format('*'*100))
        continue
    if select == 1:
        q.in_queue(input("输入新结点数据:"))
        print('*'*100)
    elif select == 2:
        if q.is_empty():
            print("队列无数据可输出\n%s"%('*'*100))
            continue
        print("弹出的数据为:")
        q.out_queue()
        print('*'*100)
    elif select ==0:
        select = 0
        break
    else:
        print("输入错误,请重新输入\n{}".format('*'*100))
print("连续输出:")       
q.out_all()

运行结果:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小文大数据

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值