2016-04-16 44 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

按字母順序比較兩個字符串,請使用strcmp()

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

cmpRecord(&n->data, &newNode->data);調用這個函數,因爲data字段的類型Record