838. Design Linked List
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to design a linked list data structure. We need to implement five core functionalities: getting a node's value by index, adding a node at the head, adding a node at the tail, adding a node at a specific index, and deleting a node at a specific index. The list is 0-indexed. We can choose between a singly or doubly linked list. A key consideration is handling edge cases such as an empty list, invalid indices, and operations at the boundaries (head and tail).
Solution
Design Linked List in Python
class MyLinkedList:
# Node class nested for encapsulation
class Node:
def __init__(self, val):
self.val = val
self.next = None
def __init__(self):
"""
Initialize your data structure here.
"""
self.size = 0
# Sentinel node to simplify edge cases
self.head = self.Node(0)
def get(self, index: int) -> int:
"""
Get the value of the index-th node in the linked list. If the index is invalid, return -1.
"""
# Check if the index is valid
if index < 0 or index >= self.size:
return -1
# Traverse from the first actual node
curr = self.head.next
for _ in range(index):
curr = curr.next
return curr.val
def addAtHead(self, val: int) -> None:
"""
Add a node of value val before the first element of the linked list.
"""
self.addAtIndex(0, val)
def addAtTail(self, val: int) -> None:
"""
Append a node of value val to the last element of the linked list.
"""
self.addAtIndex(self.size, val)
def addAtIndex(self, index: int, val: int) -> None:
"""
Add a node of value val before the index-th node in the linked list.
"""
# If index is greater than the length, the node will not be inserted
if index > self.size:
return
# Constraints state 0 <= index, this is for robustness
if index < 0:
index = 0
self.size += 1
# Find the predecessor of the node to be added
pred = self.head
for _ in range(index):
pred = pred.next
# Create and link the new node
to_add = self.Node(val)
to_add.next = pred.next
pred.next = to_add
def deleteAtIndex(self, index: int) -> None:
"""
Delete the index-th node in the linked list, if the index is valid.
"""
# Check if the index is valid
if index < 0 or index >= self.size:
return
self.size -= 1
# Find the predecessor of the node to be deleted
pred = self.head
for _ in range(index):
pred = pred.next
# Bypass the node to be deleted
pred.next = pred.next.next
Design Linked List in Java
class MyLinkedList {
// Node structure for the singly linked list
private class Node {
int val;
Node next;
Node(int val) {
this.val = val;
}
}
private int size;
private Node head; // Sentinel node
/** Initialize your data structure here. */
public MyLinkedList() {
size = 0;
head = new Node(0); // Sentinel node to simplify edge cases
}
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
public int get(int index) {
// Check if the index is valid
if (index < 0 || index >= size) {
return -1;
}
// Traverse from the first actual node
Node curr = head.next;
for (int i = 0; i < index; i++) {
curr = curr.next;
}
return curr.val;
}
/** Add a node of value val before the first element of the linked list. */
public void addAtHead(int val) {
addAtIndex(0, val);
}
/** Append a node of value val to the last element of the linked list. */
public void addAtTail(int val) {
addAtIndex(size, val);
}
/** Add a node of value val before the index-th node in the linked list. */
public void addAtIndex(int index, int val) {
// If index is greater than the length, the node will not be inserted.
if (index > size) {
return;
}
// Constraints state 0 <= index, so this is for robustness.
if (index < 0) {
index = 0;
}
size++;
// Find the predecessor of the node to be added
Node pred = head;
for (int i = 0; i < index; i++) {
pred = pred.next;
}
// Create and link the new node
Node toAdd = new Node(val);
toAdd.next = pred.next;
pred.next = toAdd;
}
/** Delete the index-th node in the linked list, if the index is valid. */
public void deleteAtIndex(int index) {
// Check if the index is valid
if (index < 0 || index >= size) {
return;
}
size--;
// Find the predecessor of the node to be deleted
Node pred = head;
for (int i = 0; i < index; i++) {
pred = pred.next;
}
// Bypass the node to be deleted
pred.next = pred.next.next;
}
}
Design Linked List in C++
class MyLinkedList {
private:
// Definition for singly-linked list node.
struct Node {
int val;
Node* next;
Node(int x) : val(x), next(nullptr) {}
};
Node* head; // Sentinel node
int size;
public:
/** Initialize your data structure here. */
MyLinkedList() {
head = new Node(0); // Initialize sentinel node
size = 0;
}
// Destructor to free the allocated memory for the list
~MyLinkedList() {
Node* curr = head;
while (curr != nullptr) {
Node* temp = curr;
curr = curr->next;
delete temp;
}
}
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
int get(int index) {
// Check if index is valid
if (index < 0 || index >= size) {
return -1;
}
// Traverse to the node at the given index
Node* current = head->next;
for (int i = 0; i < index; ++i) {
current = current->next;
}
return current->val;
}
/** Add a node of value val before the first element of the linked list. */
void addAtHead(int val) {
addAtIndex(0, val);
}
/** Append a node of value val to the last element of the linked list. */
void addAtTail(int val) {
addAtIndex(size, val);
}
/** Add a node of value val before the index-th node in the linked list. */
void addAtIndex(int index, int val) {
// If index is greater than the length, the node will not be inserted.
if (index > size) {
return;
}
// Constraints state 0 <= index, so this is for robustness.
if (index < 0) {
index = 0;
}
size++;
// Find the predecessor of the node to be added
Node* pred = head;
for (int i = 0; i < index; ++i) {
pred = pred->next;
}
// Create and link the new node
Node* toAdd = new Node(val);
toAdd->next = pred->next;
pred->next = toAdd;
}
/** Delete the index-th node in the linked list, if the index is valid. */
void deleteAtIndex(int index) {
// Check if index is valid
if (index < 0 || index >= size) {
return;
}
size--;
// Find the predecessor of the node to be deleted
Node* pred = head;
for (int i = 0; i < index; ++i) {
pred = pred->next;
}
// Bypass the node and free its memory
Node* toDelete = pred->next;
pred->next = toDelete->next;
delete toDelete;
}
};
Design Linked List in TypeScript
// The ListNode class is defined to structure the linked list.
// In a LeetCode environment, this would typically be provided or defined in the same file.
class ListNode {
val: number;
next: ListNode | null;
constructor(val?: number, next?: ListNode | null) {
this.val = (val === undefined ? 0 : val);
this.next = (next === undefined ? null : next);
}
}
class MyLinkedList {
private head: ListNode;
private size: number;
constructor() {
// Sentinel node to simplify edge cases. It doesn't hold a real value from the list.
this.head = new ListNode(0);
this.size = 0;
}
get(index: number): number {
// Check if the index is invalid
if (index < 0 || index >= this.size) {
return -1;
}
// Traverse from the first actual node
let curr = this.head.next;
for (let i = 0; i < index; i++) {
// The index check ensures curr is not null here
curr = curr!.next;
}
return curr!.val;
}
addAtHead(val: number): void {
// Adding at head is equivalent to adding at index 0
this.addAtIndex(0, val);
}
addAtTail(val: number): void {
// Adding at tail is equivalent to adding at the current size index
this.addAtIndex(this.size, val);
}
addAtIndex(index: number, val: number): void {
// If index is greater than the length, the node will not be inserted
if (index > this.size) {
return;
}
// Constraints state 0 <= index, so this is for robustness
if (index < 0) {
index = 0;
}
this.size++;
// Find the predecessor of the node to be added
let pred = this.head;
for (let i = 0; i < index; i++) {
pred = pred.next!;
}
// Create and link the new node
const newNode = new ListNode(val, pred.next);
pred.next = newNode;
}
deleteAtIndex(index: number): void {
// Check if the index is valid
if (index < 0 || index >= this.size) {
return;
}
this.size--;
// Find the predecessor of the node to be deleted
let pred = this.head;
for (let i = 0; i < index; i++) {
pred = pred.next!;
}
// Bypass the node to be deleted
pred.next = pred.next!.next;
}
}
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.