gpt4 book ai didi

c++ - 如何在 C++ 中将链表结构返回到 main?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:26:36 25 4
gpt4 key购买 nike

我正在尝试设计一个程序,该程序将从一个文件中获取输入(该文件由整数和用 空格 分隔的单词组成,它会将单词存储在链表中并在另一个列表中打印出来函数。我的问题是:如何将链表结构返回到 main() 以进行进一步处理?

struct list* createlist(FILE *m);
struct list
{
char data[30];
struct list *next;
};

using namespace std;

main()
{
char a[100], ch;
cout<<"Enter the name of the file for obtaining input.."<<endl;
cin>>a;
FILE *in;

in=fopen(a,"r");
if(in!=NULL)
{
ch=fgetc(in);
if(ch=='1')
????=createlist(in);
fclose(in);
}
return 0;
}

struct list* createlist(FILE *m)
{
cout<<"Entered createlist function..!"<<endl;
char tempStr[30];
list *curr, *head;
char c;
int i=0;
curr=NULL;
while(EOF!=(c=fgetc(m)))
{
if((c==' ') || (c=='\0'))
{
if(i==0)
{
continue;
}
tempStr[i]='\0';
i=0;
continue;
}

tempStr[i]=c;
i++;
return ????
}

我不知道怎么返回所以用问号标记,调用部分和返回部分。

最佳答案

createlist 函数中,为您想要的每个数据创建一个节点,并将其引用到前一个节点。返回指向第一个的指针。

使用malloc为每个节点分配数据,再次使用malloc为每个节点分配你需要的字符串

您可以使用示例 here和他们一样做

这里 - 应该做的工作:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

struct list* create_list(struct list *head, char *val);
struct list* add_to_list(struct list *node, char *val);
struct list* createlist(FILE *m);
struct list
{
char *data;
struct list *next;
}list;

main()
{

char a[100], ch;
struct list* obj;
cout<<"Enter the name of the file for obtaining input.."<<endl;
cin>>a;
FILE *in;

in=fopen(a,"r");
if(in!=NULL)
{

ch=fgetc(in);
if(ch=='1')
obj=createlist(in);
fclose(in);
}
return 0;
}

struct list* createlist(FILE *m)
{
cout<<"Entered createlist function..!"<<endl;
char *tempStr = (char *)malloc(30 * sizeof(char));
struct list *curr = NULL, *head = NULL;
char c;
int i=0;
curr=NULL;

while(EOF!=(c=fgetc(m)))
{
if((c==' ') || (c=='\0') || i == 29)
{
if(i==0)
{
continue;
}
tempStr[i]='\0';
i=0;
curr = add_to_list(curr, tempStr);

if(head == NULL)
{
head = curr;
}

tempStr = (char *)malloc(30 * sizeof(char));
continue;
}

tempStr[i]=c;
i++;
}
return head;
}


struct list* create_list(struct list *head, char *val)
{
printf("\n creating list with headnode as [%s]\n",val);
struct list *ptr = (struct list*)malloc(sizeof(struct list));
if(NULL == ptr)
{
printf("\n Node creation failed \n");
return NULL;
}
ptr->data = val;
ptr->next = NULL;

head = ptr;
return ptr;
}

struct list* add_to_list(struct list *node, char *val)
{
if(NULL == node)
{
return (create_list(node, val));
}

printf("\n Adding node to end of list with value [%s]\n",val);

struct list *ptr = (struct list*)malloc(sizeof(struct list));
if(NULL == ptr)
{
printf("\n Node creation failed \n");
return NULL;
}
ptr->data = val;
ptr->next = NULL;

node->next = ptr;
return ptr;
}

要知道当前的字符是否是一个整数,你可以这样做:

if(c>= '0' && c<= '9')

关于c++ - 如何在 C++ 中将链表结构返回到 main?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18446192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com