2016-10-06 2 views
0

그래서 이름을 기준으로 작고 큰 링크 된 목록을 정렬하려고합니다. 그것은 그것을 정렬하지만 역 또는 잘못된 방식으로 정렬됩니다.C 프로그래밍에서 연결된 목록을 정렬하는 방법은 무엇입니까?

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

//declaring a struct 
struct node { 
    char *name; 
    int num; 
    struct node *next; 
}; 
struct node *list=NULL; 

/* 
* insert() 
*/ 

struct node *insert(char word2[], int val){ 
    struct node *tmp; 

    tmp = malloc(sizeof(struct node)); 
    if(tmp ==NULL){ 
     fprintf(stderr, "out of memory\n"); 
     exit(1); 
    } 

    tmp->name = strdup(word2); 
    tmp->num = val; 
    tmp->next = list; 
    list = tmp; 

    return tmp; 
}//read string 

void print(){ 
    struct node *ptr; 
    for(ptr= list; ptr!=NULL; ptr = ptr->next){ 
     printf(" %s/%d\n", ptr->name, ptr->num); 
    }//for loop 
}//print 

void sort(){ 
    struct node *ptr1, *ptr2; 
    char *tmp; 

    for(ptr1 = list; ptr1!=NULL; ptr1 = ptr1->next){ 
     for(ptr2 = ptr1->next; ptr2!=NULL; ptr2 = ptr2->next){ 
      if(strcmp(ptr1->name, ptr2->name)>0){ 
       //ptr1->name is "greater than" ptr2->name - swap them 
       tmp = ptr1->name; 
       ptr1->name = ptr2->name; 
       ptr1->name = tmp; 
      } 
     } 
    } 
}//sort 

int main(){ 
    char buff[81]; 
    int status=0; 
    int len; 
    char word1[20]; 
    char word2[20]; 
    int val; 
    //  char word3[20]; 

    while(fgets(buff, 81, stdin)>0){ 
     len = strlen(buff); 

     if(buff[len-1]!='\n'){ 
      fprintf(stderr,"Error: string line length was too long\n"); 
      exit(1); 
     } 

     sscanf(buff, "%s %s %d", word1, word2, &val); 

     if(strcmp(word1, "insert")==0){ 
      insert(word2, val); 
      sort(); 
     }else if(strcmp(word1, "print")==0){ 
      print(); 
     }else{ 

     } 

    }//while loop 

    return status; 
} 

이것은 내 입력을 실행할 때의 모습입니다.

"insert a 1" 
"insert b 2" 
"insert c 3" 
"print" 

출력 내 정렬 방법 조건을 변경 시도했지만이 길을 잘못 정렬을 유지 한 경우

c/3 
b/2 
a/1 

. 나는 그 버그를 찾지 못하는 것 같습니다. 어떤 도움이라도 대단히 감사하겠습니다. 하지만 내 출력은 모든 당신이 전체 거품 정렬 한 라운드를 필요로하지 않는 삽입 정렬해도 후이

원하는 출력

a/1 
b/2 
c/3 
+3

프로그램을 디버거로 사용 해보았습니까? – kaylum

+0

어떻게 그럴 수 있습니까? –

+0

google'gdb'는 시작할 장소가 될 것입니다 – bruceg

답변

0

처럼 보이도록되어있다.

void sort() 
{ 
    struct node *ptr1 = list; 
    char *tmpname; 
    int tmpnum; 

    while (ptr1->next != NULL) { 
    if (strcmp(ptr1->name, ptr1->next->name) > 0) { 
     // swap content in this case, not the nodes 
     tmpname = ptr1->name; 
     tmpnum = ptr1->num; 

     ptr1->name = ptr1->next->name; 
     ptr1->num = ptr1->next->num; 

     ptr1->next->name = tmpname; 
     ptr1->next->num = tmpnum; 

    } 
    ptr1 = ptr1->next; 
    } 
} 
관련 문제