I have created this program about using a singly linked list class that implements several functions: Add
, Display
and Sort
.
Could you suggest me how to make my code better and which functions to include in the future?
#include <iostream>
using namespace std;
// ----------------------------------------------------
class Node {
private:
int value;
Node *next;
public:
Node(int v) { value = v; next = NULL; }
void Add(int v);
void Print();
void SortValues();
void SortNodes();
};
// ----------------------------------------------------
void Node::Add(int v)
{
Node *newItem = new Node(v);
Node *temp = this;
while (temp->next != NULL)
temp = temp->next;
temp->next = newItem;
}
void Node::Print()
{
Node *temp = this;
while (temp != NULL)
{
cout << " " << temp << " : " << temp->value << endl;
temp = temp->next;
}
}
void Node::SortValues()
{
Node *swapCandidate = next;
Node *current;
Node *min;
// L* temp;
// Look at every value
while (swapCandidate != NULL)
{
current = swapCandidate;
min = swapCandidate;
// ------------------------------
while (current != NULL)
{
if (current->value < min->value)
{
min = current;
}
current = current->next;
}
if(min != swapCandidate)
{
int tempV = min->value;
min->value = swapCandidate->value;
swapCandidate->value = tempV;
}
// ------------------------------
swapCandidate = swapCandidate->next;
}
}
// ----------------------------------------------------
void main()
{
// Sort - moving values
Node *myList = new Node(0);
myList->Add(15);
myList->Add(3);
myList->Add(20);
myList->Add(1);
myList->Print();
myList->SortValues();
cout << "------------------------------" << endl;
myList->Print();
system("pause");
}