Can anyone exaplain me this code.this runs perfectly but i cant understand how :(. i’ve approached this by creating a structure for the nodes of teh linked list. And then two functions , one for insetion at the beginniing of teh linked list and one to display the linked list.
Can one please explain the void seggregate function
#include <bits/stdc++.h>
using namespace std;
struct LLNode
{
int data;
struct LLNode* next;
};
void insertAtBeginning(struct LLNode** head, int dataToBeInserted)
{
struct LLNode* current = new LLNode;
current->data = dataToBeInserted;
current->next = NULL;
if(*head == NULL)
*head=current;
else
{
current->next=*head;
*head=current;
}
}
void display(struct LLNode**node)
{
struct LLNode *temp= *node;
while(temp!=NULL)
{
if(temp->next!=NULL)
cout<<temp->data<<" --> ";
else
cout<<temp->data;
temp=temp->next;
}
cout<<endl;
}
void Segregate(struct LLNode **head)
{
struct LLNode *end = *head;
struct LLNode *previous = NULL;
struct LLNode *current = *head;
while (end->next != NULL)
{
end = end->next;
}
struct LLNode *new_end = end;
while(current->data % 2 != 0 && current != end)
{
new_end->next = current;
current = current->next;
new_end->next->next = NULL;
new_end = new_end->next;
}
if(current->data%2 == 0)
{
*head = current;
while(current!= end)
{
if((current->data)%2 == 0)
{
previous = current;
current = current->next;
}
else
{
previous->next = current->next;
current->next = NULL;
new_end->next = current;
new_end = current;
current = previous->next;
}
}
}
else previous = current;
if (new_end!=end && (end->data)%2 != 0)
{
previous->next = end->next;
end->next = NULL;
new_end->next = end;
}
return;
}
int main()
{
struct LLNode* head = NULL;
insertAtBeginning(&head, 341);
insertAtBeginning(&head, 362);
insertAtBeginning(&head, 921);
insertAtBeginning(&head, 748);
insertAtBeginning(&head, 210);
insertAtBeginning(&head, 701);
insertAtBeginning(&head, 300);
insertAtBeginning(&head, 899);
insertAtBeginning(&head, 407);
insertAtBeginning(&head, 666);
insertAtBeginning(&head, 369);
insertAtBeginning(&head, 235);
insertAtBeginning(&head, 236);
cout<<endl;
cout<<endl;
cout<<"The Input linked list is: "<<endl;
display(&head);
Segregate(&head);
cout<<endl;
cout<<endl;
cout<<"The Final Modified linked list in such a way that all the even nodes appear at the begining of the Linked List is: "<<endl;
display(&head);
cout<<endl;
cout<<endl;
return 0;
}