Linked List Data Structure: Creation and Traversal in DSA
Introduction
A Linked List is a fundamental data structure where elements (nodes) are connected using pointers.
π Unlike arrays:
- No fixed size
- Dynamic memory allocation
- Efficient insertions
Each node contains:
- Data
- Pointer to next node
πΉ Structure of a Node
[ Data | Next ]
π Example:
10 β 20 β 30 β NULL
πΉ 1. Creation of Linked List in PHP
π§βπ» Step 1: Create Node Class
<?php
class Node {
public $data;
public $next;
public function __construct($data) {
$this->data = $data;
$this->next = null;
}
}
?>π§βπ» Step 2: Create Linked List Class
<?php
class LinkedList {
public $head;
public function __construct() {
$this->head = null;
}
// Create list by adding nodes at end
public function insert($data) {
$newNode = new Node($data);
if ($this->head == null) {
$this->head = $newNode;
return;
}
$temp = $this->head;
while ($temp->next != null) {
$temp = $temp->next;
}
$temp->next = $newNode;
}
}
?>π§ͺ Example: Creating a Linked List
<?php
$list = new LinkedList();
$list->insert(10);
$list->insert(20);
$list->insert(30);
?>π Created List:
10 β 20 β 30 β NULL
πΉ 2. Traversal of Linked List
π‘ Concept
Traversal means visiting each node one by one.
π Start from head
π Move using next pointer
π§βπ» Traversal Code
<?php
public function traverse() {
$temp = $this->head;
while ($temp != null) {
echo $temp->data . " β ";
$temp = $temp->next;
}
echo "NULL";
}
?>π§ͺ Full Example
<?php
class Node {
public $data;
public $next; public function __construct($data) {
$this->data = $data;
$this->next = null;
}
}
class LinkedList {
public $head; public function __construct() {
$this->head = null;
}
public function insert($data) {
$newNode = new Node($data);
if ($this->head == null) {
$this->head = $newNode;
return;
} $temp = $this->head;
while ($temp->next != null) {
$temp = $temp->next;
} $temp->next = $newNode;
}
public function traverse() {
$temp = $this->head;
while ($temp != null) {
echo $temp->data . " β ";
$temp = $temp->next;
} echo "NULL";
}
}// Usage
$list = new LinkedList();
$list->insert(10);
$list->insert(20);
$list->insert(30);$list->traverse();?>β‘ Time Complexity
| Operation | Complexity |
|---|---|
| Creation | O(n) |
| Traversal | O(n) |
π― Key Points
β
Linked List is dynamic
β
No index access (unlike arrays)
β
Traversal is required to access elements
No comments yet! You be the first to comment.
