Python Linked Lists


Linked List is a linear data structure where elements (called nodes) are connected using pointers.

Each node contains:

  • Data

  • A pointer to the next node

It follows a sequential order, but unlike arrays, it does not use continuous memory.


🔹 Why Use Linked Lists?

  • Dynamic size

  • Efficient insert/delete from start or middle

  • No need to shift elements (like in arrays)


🔹 Node Structure

A simple node in Python is created using a class:

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

🔹 Create a Linked List

# Define node
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

# Create linked list
node1 = Node(10)
node2 = Node(20)
node3 = Node(30)

# Connect nodes
node1.next = node2
node2.next = node3

# Traverse list
current = node1
while current:
    print(current.data)
    current = current.next

✅ Output:

10
20
30

🔹 Operations on Linked List

1. Traversal
def traverse(head):
    current = head
    while current:
        print(current.data)
        current = current.next

2. Insert at Beginning
new_node = Node(5)
new_node.next = node1  # node1 was the previous head
head = new_node

3. Insert at End
def insert_end(head, data):
    new = Node(data)
    current = head
    while current.next:
        current = current.next
    current.next = new

4. Delete a Node
def delete_node(head, key):
    if head.data == key:
        return head.next
    prev = None
    current = head
    while current and current.data != key:
        prev = current
        current = current.next
    if current:
        prev.next = current.next
    return head

Practice Questions

Q1. Write a Python program to create a linked list with 4 nodes having values: 10, 20, 30, and 40.

Q2. Write a Python program to define a function that displays all values in the linked list.

Q3. Write a Python program to insert a new node at the beginning of the linked list.

Q4. Write a Python program to insert a new node at the end of the linked list.

Q5. Write a Python program to delete a node with value 20 from the linked list.

Q6. Write a Python program to count the total number of nodes in the linked list.

Q7. Write a Python program to check if a specific value exists in the linked list.

Q8. Write a Python program to reverse the linked list.

Q9. Write a Python program to create a function that searches a node by value and returns its position.

Q10. Write a Python program to print the value of the last node in the linked list.


Go Back Top