2016-08-09 99 views
0

我使用C編寫了一個SortedInsert()函數來將新節點插入到按升序排序的給定列表中。我的SortedInsert()函數的代碼如下:鏈接列表SortedInsert()函數

#include <stdio.h> 
#include <stdlib.h> 
#include <assert.h> 


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

void push(struct node** head, int data_new) { 
    struct node* headNode; 
    headNode = (node*)malloc(sizeof(struct node)); 
    headNode->data = data_new; 
    headNode->next = *head; 
    *head = headNode; 
} 

struct node* BuildFunny() { 
    struct node*head = NULL; 
    push(&head, 2); 
    push(&head->next, 3); 
    push(&head->next->next, 8); 
    push(&head->next->next->next, 10); 
    push(&head->next->next->next->next, 15); 
    head->next->next->next->next->next = NULL; 

    return head; 
} 

void SortedInsert(struct node** headRef, struct node* newNode){ 
    if (*headRef == NULL || (*headRef)->data >= newNode->data){ 
     newNode->next = *headRef; 
     *headRef = newNode; 
    } 
    else { 
     struct node* current; 
     current = *headRef; 
     while (current->next->data <= newNode->data && current->next != NULL){ 
      current = current->next; 
     } 
     newNode->next = current->next; 
     current->next = newNode; 
    } 
} 

的主要功能是:

int main() 
{ 
    struct node* head; 
    head = BuildFunny(); 
    struct node* newNode = (struct node*)malloc(sizeof(struct node)); 
    newNode->data = 1; 
    newNode->next = NULL; 
    SortedInsert(&head, newNode); 

    struct node* newNode1 = (struct node*)malloc(sizeof(struct node)); 
    newNode1->data = 6; 
    newNode1->next = NULL; 
    SortedInsert(&head, newNode1); 

    /* 
    struct node* newNode2 = (struct node*)malloc(sizeof(struct node)); 
    newNode2->data = 20; 
    newNode2->next = NULL; 
    SortedInsert(&head, newNode2); 
    */ 

    while(head != NULL){ 
     printf("%d ", head->data); 
     head = head->next; 
    } 


    return 0; 
} 

問題是我可以正確地插入數1和6與正確的順序列表,然而數20總是給我錯誤(取消註釋newNode2會給出錯誤)。我不知道爲什麼我不能將超過15的數字插入到我的列表中。有人可以幫助我製作15歲以上的數字,還可以在列表末尾插入嗎?

+0

「給出錯誤」。如果你真的告訴我們錯誤是什麼,這將有所幫助。這是一個編譯錯誤?運行時錯誤?如果有任何錯誤信息,是什麼? – kaylum

回答

1

可能的問題是與此條件

while (current->next->data <= newNode->data && current->next != NULL) 

更改它來檢查NULL之前

while (current->next != NULL && (current->next->data <= newNode->data)) 

與您的代碼,當current->nextNULL,它會嘗試將參照第一條件NULL指針導致問題。 因此,當添加比列表中現有數字更大的數字時,您會遇到問題。