I have a bit a of a problem because I have no idea what's going on in my code. Could someone guide me with this? **It has to swap the nodes themselves.
**
#include <iostream>
#include <iomanip>
using namespace std;
typedef struct node
{
int DATA;
node *NEXT;
};
node *HEAD = NULL;
void Create(int data);
void Display();
void Sort();
int main()
{
int num, numOfEl;
cout << "Enter number of elements: ";
cin >> numOfEl;
cout << "Enter " << numOfEl << " numbers: ";
for(int i = 0 ; i < numOfEl ; i++)
{
cin >> num;
Create(num);
}
cout << "\nDisplay before sorting.\n";
Display();
node *before_i = NULL; node *i = HEAD;
while(i->NEXT != NULL)
{
node *before_j = NULL;
node *j = i;
while(j->NEXT!=NULL)
{
before_j = j;
j = j->NEXT;
if(j->DATA > i->DATA)
break;
}
if(before_j!= NULL)
{
if(i == HEAD)
{
HEAD = j;
before_j->NEXT = j->NEXT;
j->NEXT = i;
}
else
{
before_i->NEXT = j;
before_j->NEXT = j->NEXT;
j->NEXT = i;
}
}
before_i = i;
Display();
if(i->NEXT != NULL)
i = i->NEXT;
}
//Sort();
cout << "\nDisplay after sorting.\n";
Display();
}
void Sort()
{
node *k, *nwlist;
nwlist = HEAD; k = HEAD->NEXT ;
while(k != NULL)
{
Display();
node *ptr;
if(nwlist->DATA > k->DATA)
{
node *tmp;
HEAD = k;
k = k->NEXT;
HEAD->NEXT = nwlist;
nwlist->NEXT = k;
continue;
}
for(ptr = nwlist ; ptr->NEXT != NULL ; ptr = ptr->NEXT)
{
if(ptr->NEXT->DATA > k->DATA)
break;
}
if(ptr->NEXT!=NULL)
{
node *tmp;
tmp = k ;
k = k->NEXT;
ptr->NEXT = tmp->NEXT;
tmp->NEXT = ptr;
continue;
}
if(ptr->NEXT == NULL)
{
ptr->NEXT = k;
k = k->NEXT;
ptr->NEXT->NEXT = NULL;
continue;
}
}
}
void Display()
{
node *current;
current = HEAD;
cout << setw(20) << "LAST" << setw(20) << "NUMBER" << setw(20) << "NEXT" << endl;
while(current != NULL)
{
cout << setw(20) << current << setw(20) << current->DATA << setw(20) << current->NEXT << endl;
current = current->NEXT;
}
system("pause>0");
}
void Create(int data)
{
node *front, *tail;
tail = new node;
tail->DATA = data;
tail->NEXT = NULL;
if(HEAD == NULL)
HEAD = tail;
else
{
front = HEAD;
while(front->NEXT!=NULL)
front = front->NEXT;
front->NEXT = tail;
}
}