2016-04-07 2 views
0

私がやっているラボの作業では、ユーザーが文字列を入力しない限り、リンクされたリストに文字列を入力することができます。この時点で、プログラムは各文字列を最初の文字と比較し、アルファベット順に並べ替えて表示します。文字列をアルファベット順に並べたリンクリスト

私はstrcmpを使って一度に2つの文字列を比較する必要があることを知っていますが、これを理解しようとしましたが、それはとても複雑です。

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

#define StringLengthMAX 80 

struct node_link 
{ 
    //char node_string[StringLengthMAX]; 
    int num; 
    struct node_link *next; 
}; 

int compare_node(struct node_link *b1, struct node_link *b2) 
{ 
    //strcmp(*b1, *b2); 


    if (b1 -> num < b2 -> num) 
    { 
     return -1; 
    } 
    if (b1 -> num == b2 -> num) 
    { 
     return 0; 
    } 
    if (b1 -> num > b2 -> num) 
    { 
     return 1; 
    } 
} 

struct node_link *add_node(struct node_link *list, struct node_link *node) 
{ 
    struct node_link *cur_node=list; 

    //case 1 : When list->num > node->num 
    if (compare_node(list, node) == 1) 
    { 
     node -> next = list; 
     list = node; 
     return list; 
    } 
    // case 2 

    while(cur_node->next != NULL) 
    { 
     if (compare_node(cur_node->next,node) == 1) 
     { 
      node -> next = cur_node -> next; 
      cur_node->next = node; 
      break; 
     } 
     else 
     { 
       cur_node = cur_node -> next; 
     } 
    } 
    // case 3 : node->next is the greatest 
    if (cur_node -> next == NULL) 
    { 
     cur_node->next = node; 
    } 
    return list; 
} 

void display_newlist(struct node_link *head) 
{ 
    struct node_link *node=head; 
    while(node != NULL) 
    { 
     printf("%d", node->num); 
     node = node->next; 
     printf(" "); 
    } 
} 

int main() 
{ 
    int a; 
    struct node_link *head; 
    struct node_link *node; 

    node = (struct node_link*)malloc(sizeof(struct node_link)); 

    node->num = a; 
    node->next = NULL; 
    head = node; 

    do 
    { 
     puts("Please enter any number of integers, end inputs with a ZERO (0): "); 
     scanf("%d", &a); 

     node = (struct node_link*)malloc(sizeof(struct node_link)); 
     node->num = a; 
     node->next = NULL; 
     head = add_node(head,node); 
    }while(a != 0); 

    display_newlist(head); 

    return 0; 
} 
+0

変数の文字の配列によってエヴリーnumを交換してください。まず、リンクされたリストライブラリを作成して、任意の要素を挿入してリストをトラバースできるようにします。 *あなたの 'add_ *'関数を書いて、あなたのリンクリストにアクセスするために以前に書かれたリンクされたリストコードを使用させます。 –

+0

関数: 'compare_node'は' return value'で終了しない実行パスを持ちます。ステートメント。このロジックのエラーにより、コンパイラは警告を発生させます。31:1:警告。制御は 'main'()関数の非void関数[-Wreturn-type] – user3629249

+0

の終わりに達します。変数' a'は初期化されていませんので、 'node-> num = a;'は未知の ' '値を最初のノードに追加します。 – user3629249

答えて

0

あなたがこの方法で

1-その後、リターンをstrcmp機能を使用してchar配列の要素を比較してみ比較機能で文字

2 - のいずれかの配列とそのint numを交換することを行うことができます値はcompare()からの値に従います。

3 - あなたは、ロジックを分離した場合にそれが簡単になります

関連する問題