繁体   English   中英

仅使用一个头指针构造一个队列链接列表

[英]constructing a Queue linked list using only one head pointer

我试图只使用一个头指针(没有尾巴)来构造一个队列链接列表。 但我似乎无法进入列表的末尾。

示例:目前代码将是: c -> b -> a ,但是我想将其反转-a- a -> b -> c

class Node:
    '''A node for a linked list.'''

    def __init__(self, initdata):
        self.data = initdata
        self.next = None

class Queue(object):

    def __init__(self):
        self.head = None

    def enqueue(self, item):
        """Add an item onto the tail of the queue."""
        if self.head == None:
            temp = Node(item)
            temp.next = self.head
            self.head = temp
        else:
            current = self.head
            while current != None:
                current = current.next
            if current == None:
                temp = Node(item)
                temp.next = current
                current = temp

    def dequeue(self):
        if self.head == None:
            raise IndexError("Can't dequeue from empty queue.")
        else:
            current_first = self.head
            current = self.head.next
            return current_first.data

应该这样做:

class Node:
    '''A node for a linked list.'''
    def __init__(self, initdata):
        self.data = initdata
        self.next = None

class Queue(object):
    def __init__(self):
        self.head = None

    def enqueue(self, item):
        """Add an item onto the tail of the queue."""
        if self.head is None:
            self.head = Node(item)
        else:
            current = self.head
            while current.next is not None:
                current = current.next
            current.next = Node(item)

    def dequeue(self):
        if self.head is None:
            raise IndexError("Can't dequeue from empty queue.")
        else:
            first = self.head
            self.head = self.head.next
            return first.data

除了一些逻辑修复(我们需要创建一个新节点并将其存储在current.nextcurrent只是指向节点的变量)之外,请注意,我们使用is操作符来测试NoneNode构造函数来设置数据(因此我们可以创建和分配没有temp var的新节点)。

例如:

q = Queue()
q.enqueue('a')
q.enqueue('b')
q.enqueue('c')

print(q.dequeue())
print(q.dequeue())
print(q.dequeue())

输出:

a
b
c

顺便说一句,请注意这种结构需要O(N)插入时间和O(1)删除(pop)时间。 双端队列(如标准collections.deque )将在固定时间内进行插入和删除操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM