2016-04-16 13 views
0
typedef struct record 
{ 
    char name[20]; 
    char surname[20]; 
    char telephone[20]; 

}Record; 

typedef struct node 
{ 
    Record data; 
    struct node *next; 
}Node; 

Node *head = NULL; 

/* 
return positive value if *x > *y 
return negative value if *x < *y 
return 0 if *x == *y 
*/ 
int cmpRecord(const Record* x, const Record* y) { 
    if (x->name > y->name) return 1; 
    if (x->name < y->name) return -1; 
    return 0; 
} 

void addRecord(Record x) 
{ 
    Node *previousNode = NULL; 
    Node *newNode; 
    Node *n; 

    newNode = (Node*)malloc(sizeof(Node)); 
    newNode->data = x; 
    newNode->next = NULL; 

    if (head == NULL) // The list is empty 
    { 
     head = newNode; 
    } 
    else  // The list is not empty 
    { 
     n = head; 
     while (n->next != NULL) 
     { 
      if ((cmpRecord(&n->data.name, &newNode->data.name) < 0) && (cmpRecord(&n->next->data.name, &newNode->data.name) > 0)) // Insertion Sort 
      { 
       // We have to put it between these 2 nodes 
       newNode->next = n->next; 
       n->next = newNode; 
       return; 
      } 

      else 
      { 
       previousNode = n; 
       n = n->next; 
      } 
     } 
      n->next = newNode; 

    } 

} 

このコードは、人物のレコードをリストに追加し、名前に従ってアルファベット順に並べ替えることになっています。しかし、リストを表示するとき、項目はアルファベット順ではありません。問題であると想定されるのは?ありがとう PS。 cmpRecordは、挿入ソートのif文で使用されます。C:ポインタと構造体を使用して挿入ソートロジックが機能しない

+1

'>'と '<'を使用して文字列をアルファベット順にソートすることはできません。文字列が減衰するポインタの値だけを比較しています。 – Unimportant

答えて

0

、アルファベット順に2つの文字列を比較strcmp()を使用するには:

int cmpRecord(const Record* x, const Record* y) { 
    int cmp = strcmp(x->name, y->name); 
    return (cmp > 0) - (cmp < 0); 
} 

dataフィールドがRecordを入力しているため、cmpRecord(&n->data, &newNode->data);ことで、この関数を呼び出します。

関連する問題