void Insert(T data)
{
Node<T> *temp = new Node<T>(data); //Created a new node in dynamic memory
//If the list is empty
if (head == nullptr)
{
//Add it to the beginning and end of the list
head = temp;
}
else
{
//Traverse to the end of the list
Node<T>* tempT = head;
while (tempT->next != nullptr)
{
tempT = tempT->next;
}
//Attach the new node to the end of the
//list
tempT->next = temp;
}
}
Do you mean you want to order the nodes as you insert them, or sort them after you have created the list?
Either way, you need to have an ordering function (like "less-than") which can tell you which element comes first when ordered.
In the first case, when you are inserting elements, you traverse the list looking for the first element in the list that comes after new element. Simply insert the new element into the list at that point. Pay careful attention to corner cases: empty list, before first element, after last element.
In the second case, after you create the list, do a bubble sort on the elements. If two elements are out of order, swap them.
There are many sorting algorithms that suite to the job.
The trick, or decision, in sorting a linked list is how to swap elements.
If you have elements in an array, the swap requires a copy/move of elements. That can be expensive on "heavy" element types.
When you have a linked list, you can still do that but you have also option to swap by updating the links. That is more complex to write, but independent of the data element's type.
Thanks for pointing that out. For some reason I made the assumption that the OP knew how to manipulate items (specifically swap them) in a linked list. It is highly likely that this was a bad assumption.
You're right--learning how to swap elements in the list is just as valuable as learning how to sort a collection.
@OP,
Swapping elements in a linked list is actually pretty easy, but you have to pay attention to the details. Make sure you keep track what each "next" pointer is pointing to (including the nodes preceding the ones you are swapping), and make sure you end up with the pointers in a sane state. Be aware of corner cases like swapping the first and/or last node in a list.
Why do you insert at the tail of the list instead of at the head, which is far more efficient:
1 2 3 4 5
void Insert(T data)
{
Node<T> *newNode = new Node<T>(data, head);
head = newNode;
}
Keep in mind that T could be a big, complex class. To avoid the expense of making copies of T, you should pass it by const reference wherever you need a T.