I am making a sorted linked list where the user enters a number and the number is inserted into sorted position. I am currently having problems with the sort function.
class Node
{
public:
int data;
class Node *next;
Node(int info, Node *ptr = 0)
{
data = info;
next = ptr;
}
};
class Node *head = NULL;
class stack
{
private:
Node *temp;
public:
stack()
{
temp = 0;
}
bool isEmpty()
{
return temp == NULL;
}
I decided to go with an insert function(its called sort but really it just inserts a node into the linked list) which is why i have a current pointer and a previous pointer. I guess my question is am i on the right path? I am new to this so i just want a little bit of guidance to figure this out. Any tips will be appreciated.
void sort(int data)
{
class Node *born = new Node(data);
Node* current = head;
Node* previous = NULL;
//the list is empty case
if (isEmpty())
temp = born;
else
{
while (current != NULL)
{
if (current->data >= temp->data)
{
born->next = current;
temp = born;
break;
}
else
{
previous = current;
current = temp->next;
}
}
if (current == head)
{
born->next = head;
head = born;
}
else
{
born->next = current;
previous->next = born;
}
/*else
{
born->next = temp;
temp = born;
}*/
}
}
void print()
{
cout<<"stack from the top"<<endl;
for(Node *top = temp; top != 0; top=top->next)
cout << top->data << " ";
cout << endl;
/*while(temp != NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
*/
}
int pop()
{
if (isEmpty())
return -999;
int intReturn = temp->data;
Node *top;
top = temp;
temp = temp->next;
delete top;
return intReturn;
}
};
int main(void)
{
int num=0;
stack boss;
while(num!=-1)
{
cout<<"Please Enter a Number"<<endl;
cin >> num;
if (num == -1)
boss.print();
else
boss.sort(num);
}
cout<<endl<<endl;
system("PAUSE");
return 0;
}