Insertion and deletion in middle program in c++
// Program to delete middle element of a linked list
#include <iostream>
using namespace std;
// Node in a linked list
struct Node {
int val;
struct Node* next;
};
// counting the number of nodes present in the list
int count_nodes(struct Node* head)
{
int n_count = 0;
while (head != NULL) {
head = head->next;
n_count++;
}
return n_count;
}
// returns head of the newly formed list
// after deleting the middle element.
struct Node* delete_middle(struct Node* head)
{
if (head == NULL)
return NULL;
if (head->next == NULL) {
delete head;
return NULL;
}
struct Node* Head_copy = head;
// total nodes currently there in the list
int count = count_nodes(head);
// position of middle element in the list
int mid = count / 2;
// Delete the middle node
while (mid-- > 1) {
head = head->next;
}
// Delete the middle node
head->next = head->next->next;
return Head_copy;
}
// Function to display the list
void display_List(struct Node* x)
{
while (x != NULL) {
cout << x->val << "->";
x = x->next;
}
// Last element points to null
cout << "NULL\n";
}
// function to create a new node.
Node* newNode(int value)
{
struct Node* t = new Node;
t->val = value;
t->next = NULL;
return t;
}
// Driver Function
int main()
{
// Adding elements to the empty list
struct Node* head = newNode(5);
head->next = newNode(10);
head->next->next = newNode(15);
head->next->next->next = newNode(20);
head->next->next->next->next = newNode(25);
cout << "Original List" << endl;
display_List(head);
head = delete_middle(head);
cout << "List after deleting the middle element"
<< endl;
display_List(head);
return 0;
}
Comments
Post a Comment