Inserting a node
A node can be added in three ways
- At the front of the linked list
- After a given node.
- At the end of the linked list.
Add a node at the front
ListNode * LinkedList::push(ListNode *head, int data) {
ListNode *node = new ListNode(data);
node->next = head;
head = node;
return head;
}
Add a node after a given node
void LinkedList::insertAfter(ListNode *prev, int data) {
ListNode *node = new ListNode(data);
node->next = prev->next;
prev->next = node;
}
Add a node at the end
void LinkedList::append(ListNode *head, int data) {
ListNode *tail = head;
while (tail->next) {
tail = tail->next;
}
ListNode *node = new ListNode(data);
tail->next = node;
}