开发者

Linked list function that determines if values are in strictly ascending order

I have written a function below that takes a pointer to the front of a linked list and determines if the values in that list are stored in strictly ascending order. If this is the case, the function should return 1; otherwise it should return 0.

 struct listnode {
    int data;
    struct listnode* next;
 };

 int ascendingOrder(struct listnode* front) {

 struct listnode* current = front; 

 if(current->data == NULL)
    return current->data; 

 while(current->next != NULL) {

    开发者_StackOverflow中文版 if(current->data < current->next->data)
         return 1; 
     }

     else
         return 0; 

     } 
 }

Would this work, and if not how come?


I see a few things that don't look right. For starters, your version won't even compile. In addition, if the first item is less than the second item, your function returns. It doesn't even check the other items.

I'd do something more like this (untested).

int IsAscending(struct listnode* node)
{
    if (node == NULL)
        return TRUE;

    while(node->next != NULL)
    {
        if (node->data > node->next->data)
            return FALSE;
        node = node->next;
    }
    return TRUE;
}


This wouldn't work because you return after comparing the first two list items. You could put "continue;" (or just leave it blank) where your return 1 is, then put return 1 outside the while loop at the end of the program. That way it only returns 0 if it runs into a point where current > next and returns 1 if it gets through all items without that happening. Also your brackets are off, you have an extra one right after return 1. and you aren't ever changing the current node to the next node, you must set that at the bottom of the while loop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜