Here's what the task:
1.Establishment a list arranged in ascending order elements (introduced in random order) and display the list screen.
2.Delete of a user-specified element.
The code should probably be something along the lines of (by which I mean, "take this with a bagful of salt, I haven't tested it." There may especially be some exceptions I'm missing)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
void add(int num) //since the head of the list is global anyways...
{
if(start==NULL) //test to see if you're creating the list header
{
start = new elem;
start->key = num;
start->next = NULL;
}
else
{
elem* a=start;
elem* b = new elem;
while(a->next!=NULL)
a=a->next; //starts at the head of the list and works its way back
a->next = b;
b->key = num;
b->next = NULL;
}
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
void del(int num)
{
elem* a = start;
elem* b;
while(a->key!=num) //find the list element you're looking for
a=a->next;
if(a==start) //test if you need to change the list header
{
b=start->next;
delete start;
start = b;
}
else
{
b=a->next;
a->next=b->next;
delete b;
}
}
The arranging is a bit of a pain and I can't be bothered to work out a more efficient algorithm.
void arrange(void)
{
elem* a, *b;
int i=0;
while(!i) //keep going through the list over and over again until no elements are changed in an entire run
{
i=1;
a=start;
while(a!=NULL) //until the end of the list
{
b=a->next;
if(b->key<a->key)
{
a->next=b->next;
b=a;
if(a==start)
start=b;
i=0;
}
a=a->next;
}
}
}
I'm especially unsure about that last one, but it should do the trick. I think.