C++ Program For Making Middle Node Head In A Linked List
Given a singly linked list, find middle of the linked list and set middle node of the linked list at beginning of the linked list.
Examples:
Input: 1 2 3 4 5
Output: 3 1 2 4 5
Input: 1 2 3 4 5 6
Output: 4 1 2 3 5 6
The idea is to first find middle of a linked list using two pointers, first one moves one at a time and second one moves two at a time. When second pointer reaches end, first reaches middle. We also keep track of previous of first pointer so that we can remove middle node from its current position and can make it head.
C++
#include <bits/stdc++.h>
using namespace std;
class Node
{
public :
int data;
Node* next;
};
void setMiddleHead(Node** head)
{
if (*head == NULL)
return ;
Node* one_node = (*head);
Node* two_node = (*head);
Node* prev = NULL;
while (two_node != NULL && two_node->next != NULL)
{
prev = one_node;
two_node = two_node->next->next;
one_node = one_node->next;
}
prev->next = prev->next->next;
one_node->next = (*head);
(*head) = one_node;
}
void push(Node** head_ref, int new_data)
{
Node* new_node = new Node();
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList(Node* ptr)
{
while (ptr != NULL)
{
cout << ptr->data << " " ;
ptr = ptr->next;
}
cout<<endl;
}
int main()
{
Node* head = NULL;
int i;
for (i = 5; i > 0; i--)
push(&head, i);
cout << " list before: " ;
printList(head);
setMiddleHead(&head);
cout << " list After: " ;
printList(head);
return 0;
}
|
Output:
list before: 1 2 3 4 5
list After : 3 1 2 4 5
Time Complexity: O(n) where n is the total number of nodes in the linked list.
Auxiliary Space: O(1)
Please refer complete article on Make middle node head in a linked list for more details!
Last Updated :
23 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...