A linear data structure where elements are stored in nodes. Each node contains data and a pointer (next) to the next node in the sequence.
*O(1) if you have a reference to the node, otherwise O(n) to find it.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert_at_head(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def delete_node(self, key):
temp = self.head
if temp and temp.data == key:
self.head = temp.next
return
prev = None
while temp and temp.data != key:
prev = temp
temp = temp.next
if temp:
prev.next = temp.next
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
insertAtHead(data) {
const newNode = new Node(data);
newNode.next = this.head;
this.head = newNode;
}
deleteNode(key) {
let temp = this.head, prev = null;
if (temp && temp.data === key) {
this.head = temp.next;
return;
}
while (temp && temp.data !== key) {
prev = temp;
temp = temp.next;
}
if (temp) prev.next = temp.next;
}
}