Singly Linked List
Explore the ins and outs of Singly Linked List data structure in our latest blog post. From understanding the fundamentals to advanced techniques, discover how to leverage singly linked list for optimal efficiency in your coding projects.
Series: Data Structures
Episodes: (4/6)
- Stack
- Queue
- Priority Queue
- Singly Linked List
- Doubly Linked List
- Circular Queue
Introduction
A singly linked list is a fundamental data structure used in computer science and programming. It consists of a sequence of nodes, where each node stores a piece of data (often referred to as the "value" or "element") and a reference or pointer to the next node in the sequence. The last node typically points to a special value like null or None, indicating the end of the list.
Implementation
class ListNode<T> {
val: T;
next: ListNode<T> | null;
constructor(val: T) {
this.val = val;
this.next = null;
}
}
class SinglyLinkedList<T> {
head: ListNode<T> | null;
constructor() {
this.head = null;
}
append(val: T) {
const newNode = new ListNode(val);
if (!this.head) {
this.head = newNode;
return;
}
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = newNode;
}
display() {
let current = this.head;
while (current) {
console.log(current.val);
current = current.next;
}
}
search(val: T): ListNode<T> | null {
let current = this.head;
while (current) {
if (current.val === val) return current;
current = current.next;
}
return null
}
}