I was asked to create a program that enters numbers and displays the before sorting order, and the sorted order displaying the previous node address and the next node address. I was told not to swap the data inside the nodes, but move the nodes themselves. I have a problem with the sorting part because I certainly have no idea how to swap pointers. Here is my code so far:
#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();
Sort();
cout << "\nDisplay after sorting.\n";
Display();
}
void Sort()
{
node *current = HEAD, *current2 = current->NEXT, *temp;
while(current->NEXT->NEXT != NULL)
{
if(current->DATA > current->NEXT->DATA)
{
temp = current;
current = current2;
current2 = temp;
}
current = current->NEXT;
}
}
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;
}
}
If I do get any help from here, thank you very much.