如何将链表传递给C中的函数

时间:2017-05-03 19:12:45

标签: c function linked-list

所以我已经制作了一个工作程序,用于从文件中获取数据并根据您想要的所有文件的主要部分打印出文件。但我的目标是通过创建用户界面并从文件附加到链接列表或根据请求打印出该链接列表的一部分(如果有)来实现此模块化。 只有一个问题:我似乎无法找到一种方法将链接列表成功传递给函数,以便在函数(附加)中创建新节点时,它也可以在main中工作,然后再在(打印)。

这是工作代码:

#include <stdio.h>
#include <stdlib.h>      /* has the malloc prototype      */
#define TSIZE 100        /* size of array to hold title   */
struct book {
    char title[TSIZE], author[TSIZE],year[6];
    struct book * next;  /* points to next struct in list */
};
//typedef struct book ITEM;
typedef struct book * Node;     // struct book *
void Append(Node *List, Node *Lcurrent,char filename[]);
void ClearGarbage(void);
int main(void){
    Node head=NULL;
    Node current;
    current=head;
    char fname[]="HW15Data.txt";
    char op;
    do{
        puts("Select operation from the following list:");
        puts("a. Append    p. Print q. quit");
        op = getchar();
        ClearGarbage();
        if (op=='a'){
            /* Gather  and store information          */
            Append(&head,&current,fname);
        }
        else if (op=='q'){
            /* User quit, so free allocated memory */
            current = head;
            while (current != NULL)
            {
                free(current);
                current = current->next;
            }
            printf("Bye!\n");
            return 0;
        }
        else{
            /* Program done, so free allocated memory */
            current = head;
            while (current != NULL)
            {
            free(current);
            current = current->next;
            }
            printf("Invalid characted entered. Bye!\n");
            return 0;
        }
    } while (op!='q');
    return 0;
}
void Append(Node *List, Node * Lcurrent,char filename[TSIZE]){
    FILE * fp;
    Node head=*List;
    Node current=*Lcurrent;
    int loops=0;
    fp=fopen(filename,"r");
    if (head==NULL){
        head=(Node) malloc(sizeof(struct book));
        current=head;
        current->next=NULL;
    }
    do{
        current->next = (Node) malloc(sizeof(struct book));
        current=current->next;
        loops++;
    } while(fgets(current->title,sizeof(current->title),fp) && fgets(current->author,sizeof(current->title),fp) && fgets(current->year,sizeof(current->year),fp));;
    free(current);
    printf("Number of records written: %d\n",loops);
//Same as Print function in the nonworking code
    int num;
    int i=0;
    if (head == NULL){
        printf("No data entered. ");
    }
    else{
        printf("Enter record # to print: ");
        scanf("%d",&num);
        ClearGarbage();
        num=num+1;
        current = head;
        while (current != NULL && i<num)
        {
            for (i=0;i<num;i++)
                current = current->next;
            printf("Book: %sAuthor: %sYear: %s\n",
            current->title, current->author, current->year);
            }
    }
}
void ClearGarbage(void){
    while (getchar()!='\n');
}

好的酷可行,但我的猜测是,一旦Append完成,Append中的节点在main中没用,因为它们现在已经消失了。因此,当我尝试使用以下代码创建打印功能时,无需打印。

#include <stdio.h>
#include <stdlib.h>      /* has the malloc prototype      */
#define TSIZE 100        /* size of array to hold title   */
struct book {
    char title[TSIZE], author[TSIZE],year[6];
    struct book * next;  /* points to next struct in list */
};
//typedef struct book ITEM;
typedef struct book * Node;     // struct book *
void Append(Node *List, Node *Lcurrent,char filename[]);
int Print(Node *List,Node *Lcurrent);
void ClearGarbage(void);
int main(void){
    Node head=NULL;
    Node current;
    current=head;
    char fname[]="HW15Data.txt";
    char op;
    do{
        puts("Select operation from the following list:");
        puts("a. Append    p. Print q. quit");
        op = getchar();
        ClearGarbage();
        if (op=='a'){
            /* Gather  and store information          */
            Append(&head,&current,fname);
        }
        else if (op=='p'){
            /*Print book record of user's choice*/
            Print(&head,&current);
        }
        else if (op=='q'){
            /* User quit, so free allocated memory */
            current = head;
            while (current != NULL)
            {
                free(current);
            current = current->next;
            }
            printf("Bye!\n");
            return 0;
        }
        else{
            /* Program done, so free allocated memory */
            current = head;
            while (current != NULL)
            {
            free(current);
            current = current->next;
            }
            printf("Invalid characted entered. Bye!\n");
            return 0;
        }
    } while (op!='q');
    return 0;
}
void Append(Node *List, Node * Lcurrent,char filename[TSIZE]){
    FILE * fp;
    Node head=*List;
    Node current=*Lcurrent;
    int loops=0;
    fp=fopen(filename,"r");
    if (head==NULL){
        head=(Node) malloc(sizeof(struct book));
        current=head;
        current->next=NULL;
    }
    do{
        current->next = (Node) malloc(sizeof(struct book));
        current=current->next;
        loops++;
    } while(fgets(current->title,sizeof(current->title),fp) && fgets(current->author,sizeof(current->title),fp) && fgets(current->year,sizeof(current->year),fp));
    free(current);
    printf("Number of records written: %d\n",loops);
}
int Print(Node *List,Node *Lcurrent){
    int num;
    int i=0;
    Node head=*List;
    Node current=*Lcurrent;
    if (head == NULL){
        printf("No data entered.\n");
        return -1;
    }
    printf("Enter record # to print: ");
    scanf("%d",&num);
    ClearGarbage();
    num=num+1;
    current = head;
    while (current != NULL && i<num)
    {
        for (i=0;i<num;i++){
            current = current->next;
        }
        printf("Book: %sAuthor: %sYear: %s\n",
        current->title, current->author, current->year);
        }
    return 0;
}
void ClearGarbage(void){
    while (getchar()!='\n');
}

感谢任何人的帮助!

编辑:为了清晰起见,删除了未使用的typedef

1 个答案:

答案 0 :(得分:1)

似乎大多数人都把重点放在缺乏组织上(这也让我很烦恼),而不是你的实际问题。

似乎您的问题来源是您分配变量头的位置。 当你定义“Node head = * List”并且List为NULL时,因为它首次被初始化,它会丢失它与你从main发送的原始列表的连接,你只需创建一个只有本地引用的链表。

我刚刚在附加和打印功能中将“head”的用法更改为“* List”,它似乎将其排序。

这是我更改后的代码:

#include <stdio.h>
#include <stdlib.h>      /* has the malloc prototype      */
#define TSIZE 100        /* size of array to hold title   */
struct book {
    char title[TSIZE], author[TSIZE], year[6];
    struct book * next;  /* points to next struct in list */
};
//typedef struct book ITEM;
typedef struct book * Node;     // struct book *
void Append(Node *List, Node *Lcurrent, char filename[]);
int Print(Node *List, Node *Lcurrent);
void ClearGarbage(void);
int main(void) {
    Node head = NULL;
    Node current;
    current = head;
    char fname[] = "HW15Data.txt";
    char op;
    do {
        puts("Select operation from the following list:");
        puts("a. Append    p. Print q. quit");
        op = getchar();
        ClearGarbage();
        if (op == 'a') {
            /* Gather  and store information          */
            Append(&head, &current, fname);
        }
        else if (op == 'p') {
            /*Print book record of user's choice*/
            Print(&head, &current);
        }
        else if (op == 'q') {
            /* User quit, so free allocated memory */
            current = head;
            while (current != NULL)
            {
                free(current);
                current = current->next;
            }
            printf("Bye!\n");
            return 0;
        }
        else {
            /* Program done, so free allocated memory */
            current = head;
            while (current != NULL)
            {
                free(current);
                current = current->next;
            }
            printf("Invalid characted entered. Bye!\n");
            return 0;
        }
    } while (op != 'q');
    return 0;
}
void Append(Node *List, Node * Lcurrent, char filename[TSIZE]) {
    FILE * fp;
    Node head = *List;
    Node current = *Lcurrent;
    int loops = 0;
    char line[256];
    fp = fopen(filename, "r");
    if (*List == NULL) {
        *List = (Node)malloc(sizeof(struct book));
        current = *List;
        current->next = NULL;
    }
    do {
        current->next = (Node)malloc(sizeof(struct book));
        current = current->next;
        loops++;
    } while (fgets(current->title, sizeof(line), fp) && fgets(current->author, sizeof(line), fp) && fgets(current->year, sizeof(line), fp));
    free(current);
    printf("Number of records written: %d\n", loops);
}
int Print(Node *List, Node *Lcurrent) {
    int num;
    int i = 0;
    Node head = *List;
    Node current = *Lcurrent;
    if (*List == NULL) {
        printf("No data entered.\n");
        return -1;
    }
    printf("Enter record # to print: ");
    scanf("%d", &num);
    ClearGarbage();
    num = num + 1;
    current = *List;
    while (current != NULL && i<num)
    {
        for (i = 0; i<num; i++) {
            current = current->next;
        }
        printf("Book: %sAuthor: %sYear: %s\n",
            current->title, current->author, current->year);
    }
    return 0;
}
void ClearGarbage(void) {
    while (getchar() != '\n');
}

仍有许多逻辑错误和一些错误,但它修复了您要求帮助的问题。