finding the smallest number in a linked list

hello
i am trying to find the smallest number of alinked list and put it in the beginning of the list
i tried this code but no thing happens
any suggestions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 void smallest()
{
    int min;
        temp1=sptr;
        while (temp1->next!=NULL)
            {
            if (sptr->data>temp1->data)
            min=temp1->data;
            }
        temp1=sptr;
        while (temp1->data!=min)
        {
            last=temp1;
            temp1=temp1->next;
        }
        last->next=temp1->next;
        temp2=temp1;
        temp3=sptr;
        delete temp1;
        sptr=temp2;
        sptr->next=temp3;
        cout<<"DONE";

}
It doesn't appear to do anything because it's spinning in the loop at lines 5-9. Since the loop doesn't update temp1, it never exits.

Some other things:
Line 3: you haven't initialized min. I suggest you set it to the data in the first node. But before doing that, add if sptr == NULL) return; to take care of the case where the list is empty.

Line 7. You should compare against min, not sptr->data.

Line 13: last is undeclared.

Lines 16-21 don't work. This is going to sound childish but it really will work: draw a diagram of the list in black ink. Now take a different colored pen and draw in the links that change when move the min node to the front. Write the code to do what you've drawn.

By the way, note that you can actually do this is in one pass. You might want to get it working the way you're doing it now. Then SAVE A COPY OF THE FILE. Now see if you can change it to work in one pass.

Test the following cases:
- list is empty
- min value is in the middle of the list
- min value is at the beginning of the list
- min value is at the end of the list.
you aren't traversing the list

while (temp->next != NULL)
{
if (temp->info < min)
{
min = temp-> info;
temp = temp->next;
}
else
temp = temp->next;
}

you don't need to over complicate it, it should be this simple to find the smallest numb
Topic archived. No new replies allowed.