Original Post
Hello. I was making a program that would accept data and store it in a linked list in ascendind order. Here's the code: However, the list does not store numbers that should go to the last, as a sample run of the program might show: The List is: -4 8 10 Press any key to continue... Plz help me with it, any help is welcome.
//Sorted linked list
#include <iostream>
using namespace std;
class linklist
{
private:
struct node
{
int data;
node *link;
}*p;
public:
linklist();
void display();
void append(int);
void del(int);
int count();
}list1;
linklist::linklist()
{
p=NULL;
}
void linklist::display()
{
node *temp;
if(p==NULL)
cout<<"\nEmpty List!\n";
else
{
temp = new node[1];
temp = p;
cout<<"\nList is: ";
while(temp)
{
cout<<temp->data<<" ";
temp = temp->link;
}
}
}
void linklist::append(int num)
{
node *temp = new node;
node *r = new node;
temp = p;
r->data = num;
if(p==NULL || p->data>num)
{
p = r;
p->link = temp;
}
else
{
while(temp->link)
{
if((temp->data<=num)
&& (temp->link->data>num || temp->link==NULL))
{
r->link = temp->link;
temp->link = r;
return;
}
temp = temp->link;
}
}
}
void linklist::del(int num)
{
node *temp = new node;
node *r = new node;
temp = p;
if(p==NULL)
cout<<"Empty List. Nothing to delete...";
else if(p->data == num)//first node to be deleted
{
temp = p;
p = p->link;
delete temp;
}
else
{
while(temp->data != num)
{
r = temp;
temp = temp->link;
}
r->link = temp->link;
delete temp;
}
}
int linklist::count()
{
int count=0;
node *temp;
if(p==NULL)
return 0;
else
{
temp = new node;
temp = p;
while(temp)
{
count++;
temp = temp->link;
}
return count;
}
}
int main()
{
cout<<"\nAdding 10, 8, 34, 19, -4 to list.";
cout<<"\nDone.";
list1.append(10);
list1.append(8);
list1.append(34);
list1.append(19);
list1.append(-4);
list1.display();
cout<<'\n';
system("PAUSE");
return 0;
}