简体   繁体   中英

How to select the first node in linked list?

I want to select the first node in the linked list and present the selected node. This is the whole code that I've created. The "prepend" adds the node before the first node. The "append" adds the node after the last of the linked list.

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())
    

I can get the result of Jody . But if instead, I test for

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

It shows False . What is the reason?

names.pop_start() returns a Node object. Its data is the string 'Jodie' , and because of how you've defined its __str__ method, when you print the node, the string is what you'll see. But the node itself is a node, not a string.

If you compare to the data attribute:

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

...you'll get True , as intended. But it would probably make more sense for pop_start to just return the data anyway, rather than the Node object. Here's how you could do that:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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