Sorting a linked list in C

前端 未结 5 1479
北恋
北恋 2020-12-09 23:01

I\'m trying to sort a linked list by finding the largest value, deleting it from its position, and then inserting it at the top of the list.

The difficulty I\'m runn

5条回答
  •  被撕碎了的回忆
    2020-12-09 23:43

    The following are some of the problems which exist in your sorting logic:

    1. You are setting the prev pointer to curr in the beginning of the loop itself which is incorrect. By doing this, you are making the current pointer and the previous node pointer as same which makes it impossible to delete the node.
    2. You should assign the largest pointer also to top whereby it facilitates the possibility of setting the largest->next to real top node.

    The code can modified like below (Just a pointer, you need to check for other issues yourself):

    while(curr != NULL)
    {
    
        if(curr->num > largest->num)
        {
            largest = curr;
            prev->next = curr->next;
            largest->next = top;
            top = largest;
    
        }
        prev = curr;
        curr = curr->next;
    }
    

提交回复
热议问题