C程序:从递归排序函数打印链接列表

时间:2014-04-11 05:07:11

标签: c recursion linked-list

我通过读取文本文件并在列表中按字母顺序插入字母来创建链接列表。我需要打印列表,但似乎无法获得正确的功能。我一直收到错误

error: invalid type argument of ‘->’ (have ‘order_list’)
error: invalid type argument of ‘->’ (have ‘order_list’)

我知道这是不正确的,但我无法正确说明print_alph函数。任何帮助找到正确打印我的列表的方法将不胜感激。

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

typedef struct list_node_alph {
    int key;
    struct list_node_alph *rest_old;
} list_node_order; 

typedef struct {
    list_node_order *the_head;
    int size;
} order_list;

list_node_order *rec_alph_order(list_node_order * old_list, int new_key);
void insert_node(order_list *the_alph, int key);
void print_alph(order_list my_list);

list_node_order *rec_alph_order(list_node_order *old_list, int new_key) {
    list_node_order *new_list;

    if (old_list == NULL) {
            new_list = (list_node_order *)malloc(sizeof (list_node_order));
            new_list->key = new_key;
            new_list->rest_old = NULL;
    } else if (old_list->key >= new_key) {
            new_list = (list_node_order *)malloc(sizeof (list_node_order));
            new_list->key = new_key;
            new_list->rest_old = old_list;
    } else {
            new_list = old_list;
            new_list->rest_old = rec_alph_order(old_list->rest_old, new_key$
    }
    return (new_list);
}

void insert_node(order_list * the_alph, int key) {
    ++(the_alph->size);
    the_alph->the_head = rec_alph_order(the_alph->the_head, key);
}

void print_alph(order_list my_list) {
    printf("Pangram in alphabetical order: ");
    while(my_list->head != NULL) {    //ERROR
            printf("%c", my_list->the_head);    //ERROR
    }
}

int main(void) {
    int ch_count;
    int count_pangram;
    char *pang_arr;
    FILE *alph_text;

    alph_text = fopen("pangram.txt", "r");
    if (alph_text == NULL) {
            printf("Empty file. \n");
    }
    order_list my_alph = {NULL, 0};
    while (( ch_count = fgetc(alph_text)) != EOF) {
            putchar(ch_count);
            char next_key;
            int the_count;

            for (the_count = 0; the_count < 100; the_count++) {
                    if (fscanf(alph_text, "%c", &next_key) != ' ') {
                    //order_list my_alph = {NULL, 0};
                    //for(next_key; next_key != SENT; scanf("&c", &next_key$
                    insert_node(&my_alph, next_key);
                    }
            }
    }
    print_alph(my_alph);
    fclose(alph_text);
    return(0);
}

2 个答案:

答案 0 :(得分:2)

你需要使用。而不是 - &gt;在 print_alph 内部,因为您没有将order_list作为指针传递

void print_alph(order_list my_list){
    printf("Pangram in alphabetical order: ");
    while(my_list.head != NULL){
            printf("%c", my_list.the_head);
    }
}

答案 1 :(得分:2)

这里在print_alph()中传递order_list类型的实例 要访问其成员,您应使用.而不是->

所以改变

  while(my_list->head != NULL){

  while(my_list.the_head != NULL){

但我认为不应该传递它的实例,而应该在print_alph()中传递该对象的指针 在这种情况下,->可以访问其成员。

void print_alph(order_list *my_list)

并将其命名为

print_alph(&my_alph);