C:单链表排序分段故障

时间:2015-01-26 04:01:39

标签: c sorting pointers linked-list

void List_sort (struct nodeStruct **headRef){
    struct nodeStruct *tempNode = *headRef;
    struct nodeStruct *nextNode, *smallestNode;
        while (tempNode != NULL){
            nextNode = tempNode->next;
            smallestNode = tempNode;
            while (nextNode != NULL){
                if (nextNode->item < smallestNode->item) {
                    smallestNode = nextNode->next;
                }
                nextNode = nextNode->next;
            }
            int tempInt = tempNode->item;
            tempNode->item = smallestNode->item;
            smallestNode->item = tempInt;
            tempNode = tempNode->next;
        }   
}

不知道它为什么会产生seg错误,因此不应该编辑NULL。 Segmentation fault. 0x00000000004008d4 in List_sort (headRef=0x7fffffffe458) at list.c:130 130 tempNode->item = smallestNode->item; 任何人都知道为什么要这样做?

更新 执行了建议而没有更多的seg错误,但是没有正确排序。

Value: 1
Value: 2
Value: 7
Value: 3
Value: 4
Value: 6
Value: 5
Value After Sort: 1
Value After Sort: 2
Value After Sort: 4
Value After Sort: 3
Value After Sort: 5
Value After Sort: 6
Value After Sort: 7

1 个答案:

答案 0 :(得分:1)

这是不对的:

            if (nextNode->item < smallestNode->item) {
                smallestNode = nextNode->next;
            }

它应该是:

            if (nextNode->item < smallestNode->item) {
                smallestNode = nextNode;
            }