Skip to main content
Practice

Creating a Linked List Structure Using Nodes

A Linked List is a data structure where data elements are organized into individual units called Nodes which are interconnected.

Each node is made up of Data and a Pointer pointing to the next node.


Structure and Characteristics of Linked Lists

Linked lists have the following structure and characteristics.


Node

The basic unit of a linked list.

Each node contains data and one or two pointers that reference the next node (and sometimes the previous node).


A pointer that references the first node of the linked list.

It signifies the starting point of the linked list.


Tail

A pointer that references the last node of the linked list.

The pointer in the tail node generally points to None.


How can linked lists be implemented?

Below is a Python example that implements a Singly Linked List.

Example of a Singly Linked List in Python
class Node:
def __init__(self, data):
# Node data
self.data = data
# Pointer to the next node
self.next = None

class LinkedList:
def __init__(self, data):
# Create the first node
self.head = Node(data)
# Initially, head and tail are the same
self.tail = self.head

def append(self, data):
# Create a new node and link it
node = Node(data)
# Link the new node to the tail node
self.tail.next = node
# Set the new node as the tail
self.tail = node

def print_all(self):
# Print the linked list
node = self.head

# Traverse the nodes while printing data
while node:
print(node.data, end=" ")
node = node.next
print()

# Create the linked list
linked_list = LinkedList(5)

# Add nodes
linked_list.append(12)
linked_list.append(7)

# Print the linked list
linked_list.print_all()
# Output: 5 12 7

What types of linked lists are there?

Linked lists are categorized according to how nodes are connected.


Singly Linked List

The simplest form of a linked list is a singly linked list, where each node points only to the next node.


Doubly Linked List

In a doubly linked list, each node contains pointers to both the previous and next nodes.

Allows bidirectional traversal, making insertion and deletion more efficient.


Circular Linked List

In a circular linked list, the last node points to the first node, forming a continuous loop.

Useful for cyclic iterations.


Comparison between Linked Lists and Arrays

CharacteristicLinked ListArray
Memory AllocationDynamically allocates memoryUses a contiguous block of memory
Insertion/DeletionFast insertion/deletion at specific positionsInefficient insertion/deletion at specific positions
Random AccessCan only be accessed sequentiallyInstant access via indexing

Linked lists excel in memory management and efficient insertion/deletion operations, whereas arrays are better for random access and faster data processing.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.