Home > database >  Problem understanding Linked Lists in Python
Problem understanding Linked Lists in Python

Time:11-03

I'm learning about data structures and algorithms and I'm starting to learn about constructing linked lists from scratch in python. Right now I understand how they work and the components that go into making them (Nodes, data/address, Head/Tail, etc), but I'm having a really hard time wrapping my brain around how they function when constructing them in python. Like I have working code to make them in python here but I don't get the logic behind how they operate with classes. For example, I'm confused in my addLast-function on how the node variable(node = Node(value)) connects to the Node class.

class Node:
    def __init__(self, value, next=None):
        self.value = value
        self.next = next

class LinkedList:
    def __init__(self):
        self.head = None
        self.tail = None
    
    def addLast(self, value):
        node = Node(value)
        if self.head == None:
            self.head = node
            self.tail = node
        else:
            self.tail.next = node
            self.tail = node

CodePudding user response:

I think this may help you understand what the code actually do hedind the scenes.

You can paste the following code to the link and click the "Visualize Execution" button. It will visualize all details step by step.

Good Luck!

class Node:
    def __init__(self, value, next=None):
        self.value = value
        self.next = next

class LinkedList:
    def __init__(self):
        self.head = None
        self.tail = None
    
    def addLast(self, value):
        node = Node(value)
        if self.head == None:
            self.head = node
            self.tail = node
        else:
            self.tail.next = node
            self.tail = node
            
head = LinkedList()
head.addLast(1)
head.addLast(2)

CodePudding user response:

class Node:
    def __init__(self, value, next=None):
        self.value = value
        # NODE POINTS TO THE NEXT ELEMENT IF PROVIDED ELSE NONE
        self.next = next

class LinkedList:
    def __init__(self):
        # INIT AN EMPTY LINKED LIST
        self.head = None
        self.tail = None
    
    def addLast(self, value):
        # CREATE A NODE OBJECT WITH VALUE 'value' WHICH POINTS TO NOTHING (because it's the end of the linked list)
        node = Node(value)
        # IF NO HEAD IT BECOMES THE HEAD AND THE TAIL
        if self.head == None:
            self.head = node
            self.tail = node
        else:
            # ADD THE NODE TO THE END (tail) OF THE LINKED LIST
            self.tail.next = node
            self.tail = node

# Create an empty linked_list
head = Linked_list()
# Add at the end a node with the value 1
head.addLast(1)

Hope it's clearer for you, ask questions if needed

  • Related