Linked Constructor

0

Step 1: Create the Node Class

A node stores:

  • The value of the data.

  • A pointer (reference) to the next node.

Each node is like:

"value": 4,
"next": None

But in Python (using a class):

class Node:
       def __init__(self, value):
            self.value = value # stores the data
           self.next = None # pointer to the next node

So every time you create a new node:

node1 = Node(4)
print(node1.value) # 4
print(node1.next) # None

🪢 Step 2: Create the LinkedList Class (Constructor)

Now, the LinkedList class manages all nodes — it keeps track of:

  • The head (first node)

  • The tail (last node)

  • The length (total number of nodes)

Here’s the constructor:

class LinkedList:
   def __init__(self, value):
        new_node = Node(value) # create the first node
        self.head = new_node # head points to the new node
       self.tail = new_node # tail also points to it (since there’s only one)
       self.length = 1 # we start with 1 item

So when you create a linked list:

my_linked_list = LinkedList(4)

👉 It automatically builds this structure in memory:

Head[4 | None]Tail
Length = 1

🧩 Step 3: Verify the Constructor Works

Let’s print the value of the head node:

print(my_linked_list.head.value) # Output: 4
print(my_linked_list.tail.value) # Output: 4
print(my_linked_list.length) # Output: 1

✅ Full Working Code

Here’s the entire snippet you can run in VS Code:

class Node:
     def __init__(self, value):
           self.value = value
          self.next = None
class LinkedList:
     def __init__(self, value):
          new_node = Node(value)
          self.head = new_node
          self.tail = new_node

         self.length = 1

# Create a new linked list

my_linked_list = LinkedList(4)

# Print the head node’s value


print("Head Value:", my_linked_list.head.value)
print("Tail Value:", my_linked_list.tail.value)
print("Length:", my_linked_list.length)

🧠 Concept Recap

Concept Description
Node Basic unit containing value and next.
LinkedList A chain of nodes linked by pointers.
Head Reference to the first node.
Tail Reference to the last node.
Length Total nodes in the list.

Next up, you’ll typically add methods like:

  • .append(value) → Add node at the end

  • .prepend(value) → Add node at the beginning

  • .insert(index, value) → Insert node at any position

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to Top