2014-05-17 2 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; 
     } 
    } 
} 

제 실수는 무엇입니까? 삽입시이 목록을 정렬하고 싶습니다.

+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

관련 문제