2014-05-17 118 views
-5

這是我的代碼。它不起作用:爲什麼我的排序代碼不能在c中工作?

void insertioon (int d) // this part, insert and sort list 
{      
    struct node *np, *temp, *prev; 
    int found; 

    np=malloc(sizeof(struct node)); 
    np->data = d; 
    np->nextPtr = NULL; 

    temp=firstPtr; 
    found=0; 
    while ((temp != NULL) && !found) 
    { 

     if (temp->data <d) 
     { 
      prev = temp; 
      temp = temp->nextPtr; 
     } 
     else 
     { 
      found=1; 
     } 

     if (prev == NULL) 
     { 
      np->nextPtr=firstPtr; 
      firstPtr=np; 
     } 
     else 
     { 
      prev->nextPtr = np; 
      np->nextPtr = temp; 
     } 
    } 
} 

我的錯誤是什麼?在insertioon中,我想對這個列表進行排序。

+0

while循環中的插入操作。和'prev'未初始化。 – BLUEPIXY

+0

@BLUEPIXY但我寫prev = temp;我初始化爲 – user3142663

+0

在進入循環之前,您必須初始化爲NULL。 – BLUEPIXY

回答

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

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

struct node *firstPtr = NULL; 

void insertioon (int d){ 
    struct node *np, *temp, *prev = NULL; 
    int found; 

    np=malloc(sizeof(struct node)); 
    np->data = d; 
    np->nextPtr = NULL; 

    temp=firstPtr; 
    found=0; 
    while ((temp != NULL) && !found) 
    { 

     if (temp->data <d) 
     { 
      prev = temp; 
      temp = temp->nextPtr; 
     } 
     else 
     { 
      found=1; 
     } 
    } 
    if (prev == NULL) 
    { 
     np->nextPtr=firstPtr; 
     firstPtr=np; 
    } 
    else 
    { 
     prev->nextPtr = np; 
     np->nextPtr = temp; 
    } 
} 

void print_list(struct node *np){ 
    while(np){ 
     printf("%d ", np->data); 
     np=np->nextPtr; 
    } 
} 

int main(){ 
    insertioon(10); 
    insertioon(5); 
    insertioon(7); 
    insertioon(1); 
    insertioon(16); 
    print_list(firstPtr);//1 5 7 10 16 
    printf("\n"); 
    return 0; 
} 
+0

http://ideone.com/ULYI3C – BLUEPIXY

+0

非常感謝你,現在它工作。我嘗試使用隨機的10個數字。我希望我能做到這一點:) – user3142663

相關問題