在python中使用链表的最简单方法是什么?在方案中,链表简单地由'(1 2 3 4 5)
定义。事实上,Python的列表[1, 2, 3, 4, 5]
和元组(1, 2, 3, 4, 5)
并不是链表,并且链表具有一些很好的属性,比如常量时间连接,并且能够引用它们的不同部分。让它们成为不可变的,它们真的很容易使用!
发布于 2008-11-11 21:45:31
对于某些需要,deque可能也很有用。你可以在队列的两端添加和删除物品,成本为O(1)。
from collections import deque
d = deque([1,2,3,4])
print d
for x in d:
print x
print d.pop(), d
发布于 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()
发布于 2010-08-22 00:04:52
公认的答案是相当复杂的。下面是一个更标准的设计:
L = LinkedList()
L.insert(1)
L.insert(1)
L.insert(2)
L.insert(4)
print L
L.clear()
print L
它是一个简单的LinkedList
类,它基于Thomas Watnedal推荐的简单的C++设计和Chapter 17: Linked lists。
class Node:
def __init__(self, value = None, next = None):
self.value = value
self.next = next
def __str__(self):
return 'Node ['+str(self.value)+']'
class LinkedList:
def __init__(self):
self.first = None
self.last = None
def insert(self, x):
if self.first == None:
self.first = Node(x, None)
self.last = self.first
elif self.last == self.first:
self.last = Node(x, None)
self.first.next = self.last
else:
current = Node(x, None)
self.last.next = current
self.last = current
def __str__(self):
if self.first != None:
current = self.first
out = 'LinkedList [\n' +str(current.value) +'\n'
while current.next != None:
current = current.next
out += str(current.value) + '\n'
return out + ']'
return 'LinkedList []'
def clear(self):
self.__init__()
https://stackoverflow.com/questions/280243
复制相似问题