链表python

2022/6/25 1:22:21

本文主要是介绍链表python,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

链表中的任意节点包括两部分,数据部分和链接到下一个节点的部分。

# 定义节点类
class Node(object):
    def __init__(self, data = None, next = None):
        self.data = data
        self.next = next
        
class LinkedList(object):
    def __init__(self):
        self.head = Node()
        self.length = 0
        
    def isEmpty(self):
        return self.length == 0
    
    def append(self, value):
        node = Node(value)
        if self.isEmpty():
            self.head.next = node
            self.length += 1
        else:
            cur = self.head
            while cur.next is not None:
                cur = cur.next
            cur.next = node
            self.length += 1
    def print_l(self):
        print(self.length)
    def travel(self):
        cur = self.head
        i = 1
        while i <= self.length:
            print(cur.next.data)
            cur = cur.next
            i = i + 1

a = LinkedList()
a.append(3)
a.append(5)
a.travel()  


这篇关于链表python的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程