Write a pseudo c/c++ code to insert node into single linked list (start, middle, end) also write a pseudo c/c++ code to delete a node from single linked list (start, middle, end)
Answers
Answer:
To add a node in the starting :
void push(Node** head_ref, int new_data)
{
/* 1. allocate node */
Node* new_node = new Node();
/* 2. put in the data */
new_node->data = new_data;
/* 3. Make next of new node as head */
new_node->next = (*head_ref);
/* 4. move the head to point to the new node */
(*head_ref) = new_node;
}
To delete a node from a single linked list :
struct Node* deleteMid(struct Node *head)
{
// Base cases
if (head == NULL)
return NULL;
if (head->next == NULL)
{
delete head;
return NULL;
}
// Initialize slow and fast pointers to reach
// middle of linked list
struct Node *slow_ptr = head;
struct Node *fast_ptr = head;
// Find the middle and previous of middle.
struct Node *prev; // To store previous of slow_ptr
while (fast_ptr != NULL && fast_ptr->next != NULL)
{
fast_ptr = fast_ptr->next->next;
prev = slow_ptr;
slow_ptr = slow_ptr->next;
}
//Delete the middle node
prev->next = slow_ptr->next;
delete slow_ptr;
return head;
}