繁体   English   中英

如何 select 链表中的第一个节点?

[英]How to select the first node in linked list?

我想 select 链表中的第一个节点并呈现所选节点。 这是我创建的全部代码。 “前置”在第一个节点之前添加节点。 “追加”在链表的最后一个之后添加节点。

class Node:
    def __init__(self, data=None, next=None):
        self.data = data
        self.next  = next
    
    def __str__(self):
        return str(self.data)

# LinkedList definition here

class LinkedList:
    def __init__(self):
        self.head = None
        self.tail = None
    
    def prepend(self, data):
        node = Node(data, self.head)

        if self.head is None:
            self.head = node
            self.tail = node
        else:
            node.next = self.head
            self.head = node
    
    def append(self, data):
        node = Node(data, None)
        
        if self.tail is None:
            # No elements in list
            self.head = node
            self.tail = node
        else:
            self.tail.next = node
            self.tail = node
    
    def pop_start(self):
        if self.head is None:
            return None
        if self.head.next is None:
            cur = self.head
            self.head = None
            return cur 
        else:     
            if self.head != None:    
                temp = self.head
                self.head = self.head.next
                return temp
    
names = LinkedList()
names.append("Bill Gates")
names.append("Steve Jobs")
names.prepend("Jody")
print(names.pop_start())
    

我可以得到Jody的结果。 但如果相反,我测试

print(names.pop_start() == "Jody")

它显示False 是什么原因?

names.pop_start()返回一个节点 object。 它的data是字符串'Jodie' ,并且由于您定义了它的__str__方法,当您打印节点时,您将看到该字符串。 但是节点本身是一个节点,而不是一个字符串。

如果您比较data属性:

print(names.pop_start().data == "Jody")

...你会得到True ,如预期的那样。 但无论如何, pop_start只返回数据可能更有意义,而不是节点 object。 您可以这样做:

def pop_start(self):
    if self.head is None:
        return None
    else:
        data = self.head.data
        if self.head is self.tail:
            self.tail = None
        self.head = self.head.next
        return data

暂无
暂无

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

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