Well after searching high and low I can't seem to get this figured out. Im trying to sort a singly linked list and can't seem to do it correctly. So far this is my code, it uses templates and instead of pointing to null it points back to the original sentinel node with name head.
Node ( const T &initItem, Node<T> *ptr ) {item = initItem, next = ptr; }
// Data members
T item; // Node data item
Node *next; // Pointer to the next node
ptr is changed by having it run along the list, if it is not changed please point out where, but with each iteration of the loop it should add items until it does not have any items to add which will then allow ptr to equal head.
I take that to mean that ptr is used to iterate through the list, but it clearly is not so I'm wondering if I took it incorrectly.
if it is not changed please point out where
It's difficult to point out where something doesn't happen. If I wanted to point out when I didn't win the lottery, for instance, I'd have a lifetime of years to choose from, just as I could choose from any statement in the snippet I referred to. What would be more productive would be for you to point out where it does happen.
Ok, let me ask it this way. What would be a efficient way to set up a sorted linked list using the SimpList class? I can not work out the logic between adding the pointers and doing them in order all while constructing the list at the same time. I know I will need two pointers but can not figure out how to build and sort at the same time.
What would be a efficient way to set up a sorted linked list using the SimpList class?
What is efficient? Should it be efficient for people who need the list to always be sorted? Should it be efficient for people who rarely need the list to be sorted?
Assuming that you always want the list to be sorted, the insert function would look something like:
template <typename T>
void SimpList<T>::insert ( const T &newitem )
{
Node<T>* newNode = new Node<T>(newitem, nullptr) ;
// empty list.
if ( length++ == 0 )
{
head = newNode ;
return ;
}
// insertion at head:
if ( newNode->item < head->item )
{
newNode->next = head ;
head = newNode ;
return ;
}
// insertion somewhere after the head.
Node<T>* insertionPoint = head ;
while ( insertionPoint->next && insertionPoint->next->item < newNode->item )
insertionPoint = insertionPoint->next ;
newNode->next = insertionPoint->next ;
insertionPoint->next = newNode ;
}
Note that I don't see much point in the Phony data member, so this depends on head being equal to nullptr when empty. Phony seems like an unnecessary complication to me.