Leetcode 707. Design Linked List
Design your implementation of the linked list. You can choose to use a singly or doubly linked list.
Implement the MyLinkedList
class:
MyLinkedList()
Initializes the MyLinkedList
object.int get(int index)
Get the value of the index
-th node in the linked list. If the index is invalid, return -1
.void addAtHead(int val)
Add a node of value val
before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.void addAtTail(int val)
Append a node of value val
as the last element of the linked list.void addAtIndex(int index, int val)
Add a node of value val
before the index
-th node in the linked list. If index
equals the length of the linked list, the node will be appended to the end of the linked list. If index
is greater than the length, the node will not be inserted.void deleteAtIndex(int index)
Delete the index
-th node in the linked list, if the index is valid.We’ll implement a singly linked list using the given specifications.
public class MyLinkedList {
// Basic structure for a node in singly linked list
private class Node {
int val;
Node next;
Node(int val) {
this.val = val;
this.next = null;
}
}
private Node head; // Points to the head (first node) of the list
private int size; // Tracks the size of the linked list
public MyLinkedList() {
head = null;
size = 0;
}
public int get(int index) {
if (index < 0 || index >= size) {
return -1; // Invalid index
}
Node current = head;
for (int i = 0; i < index; i++) {
current = current.next;
}
return current.val;
}
public void addAtHead(int val) {
Node newNode = new Node(val);
newNode.next = head;
head = newNode;
size++;
}
public void addAtTail(int val) {
Node newNode = new Node(val);
if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
size++;
}
public void addAtIndex(int index, int val) {
if (index > size) return; // Out of bounds
if (index <= 0) {
addAtHead(val);
return;
}
if (index == size) {
addAtTail(val);
return;
}
Node newNode = new Node(val);
Node current = head;
for (int i = 0; i < index - 1; i++) {
current = current.next;
}
newNode.next = current.next;
current.next = newNode;
size++;
}
public void deleteAtIndex(int index) {
if (index < 0 || index >= size) return; // Invalid index
if (index == 0) {
head = head.next;
} else {
Node current = head;
for (int i = 0; i < index - 1; i++) {
current = current.next;
}
current.next = current.next.next;
}
size--;
}
}
By implementing solutions based on these strategies, we can efficiently solve the problem of managing a custom linked list.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?