在python中使用链表的最简单方法是什么?在方案中,链表简单地由'(1 2 3 4 5)定义。事实上,Python的列表[1, 2, 3, 4, 5]和元组(1, 2, 3, 4, 5)并不是链表,并且链表具有一些很好的属性,比如常量时间连接,并且能够引用它们的不同部分。让它们成为不可变的,它们真的很容易使用!
发布于 2008-11-11 07:54:49
前几天我写了这篇文章
#! /usr/bin/env python
class Node(object):
def __init__(self):
self.data = None # contains the data
self.next = None # contains the reference to the next node
class LinkedList:
def __init__(self):
self.cur_node = None
def add_node(self, data):
new_node = Node() # create a new node
new_node.data = data
new_node.next = self.cur_node # link the new node to the 'previous' node.
self.cur_node = new_node # set the current node to the new one.
def list_print(self):
node = self.cur_node # cant point to ll!
while node:
print node.data
node = node.next
ll = LinkedList()
ll.add_node(1)
ll.add_node(2)
ll.add_node(3)
ll.list_print()https://stackoverflow.com/questions/280243
复制相似问题