Skip to content

Operations on a linked list

Course: Linked List - chapter 2

Node* addNodeAtBeginning(Node *head, int newData) {
// As we are entering in beginning, the current head becomes the
// next node of new node. Even works when head = NULL
Node *node = new Node(newData, head);
head = node;
return head;
}
int removeNodeAtBeginning(Node *head) {
// Assuming it is a valid operation, i.e. there is atleast a single node
Node *curr = head;
head = head->next;
int data = curr->data;
delete curr;
return data;
}
int removeNodeAtEnd(Node *head) {
Node *curr = head;
Node *prev = NULL;
if (head->next == NULL) {
// Single node
head = NULL;
}
while(curr->next != NULL) {
prev = curr;
curr = curr->next;
}
if (prev != NULL) {
prev->next = NULL;
}
int data = curr->data;
delete curr;
return data;
}

Assume, every node has a distinct data value. We want to delete the node that has a value of K.

Whenever we are deleting a node, make sure to adjust the next pointer of the previous node correctly. Let’s consider all 3 cases:

  1. K is the first node: In this case, the node with K is not linked to next of any node. This becomes same as removing node from beginning.
  2. K is somewhere in middle: In this case, K is the next of some node and also the node with K has a next node. As K is getting deleted, the previous node’s next value should point to the next of K i.e prev->next = node->next.
  3. K is at end: In this case, K is the next of some node, but K has no next node. However, the above statement (2) still holds true, as prev→next = node→next = NULL. Also, if there is a tail pointer, we should adjust it
void deleteNode(Node *head, int K) {
if (head->data == K) {
Node *curr = head;
head = head->next;
delete curr;
return;
}
Node *curr = head;
Node *prev;
while(curr != NULL && curr->data != K) {
prev = curr;
curr = curr->next;
}
if (curr == NULL) return;
prev->next = curr->next;
delete curr;
}