首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python链表

Python链表
EN

Stack Overflow用户
提问于 2008-11-11 07:31:21
回答 25查看 326.5K关注 0票数 186

在python中使用链表的最简单方法是什么?在方案中,链表简单地由'(1 2 3 4 5)定义。事实上,Python的列表[1, 2, 3, 4, 5]和元组(1, 2, 3, 4, 5)并不是链表,并且链表具有一些很好的属性,比如常量时间连接,并且能够引用它们的不同部分。让它们成为不可变的,它们真的很容易使用!

EN

回答 25

Stack Overflow用户

发布于 2008-11-11 21:45:31

对于某些需要,deque可能也很有用。你可以在队列的两端添加和删除物品,成本为O(1)。

代码语言:javascript
复制
from collections import deque
d = deque([1,2,3,4])

print d
for x in d:
    print x
print d.pop(), d
票数 160
EN

Stack Overflow用户

发布于 2008-11-11 07:54:49

前几天我写了这篇文章

代码语言:javascript
复制
#! /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()
票数 72
EN

Stack Overflow用户

发布于 2010-08-22 00:04:52

公认的答案是相当复杂的。下面是一个更标准的设计:

代码语言:javascript
复制
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

代码语言:javascript
复制
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__()
票数 36
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/280243

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档