我在使用这个程序时遇到了一些麻烦。我想我几乎没有,除了它在屏幕上打印垃圾这一事实:(
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define strsize 30
typedef struct member
{
int number;
char fname[strsize];
struct member *next;
} RECORD;
RECORD* insert (RECORD *it);
RECORD* print(RECORD *it, int j);
int main (void)
{
int i, result;
RECORD *head, *p;
head=NULL;
printf("Enter the number of characters: ");
scanf("%d", &result);
for (i=1; i<=result; i++)
head=insert (head);
print (head, result);
return 0;
}
RECORD* insert (RECORD *it)
{
RECORD *cur, *q;
int num;
char junk;
char first[strsize];
printf("Enter a character:");
scanf("%c", &first);
cur=(RECORD *) malloc(sizeof(RECORD));
strcpy(cur->fname, first);
cur->next=NULL;
if (it==NULL)
it=cur;
else
{
q=it;
while (q->next!=NULL)
q=q->next;
q->next=cur;
}
return (it);
}
RECORD* print(RECORD *it, int j)
{
RECORD *cur;
cur=it;
int i;
for(i=1;i<=j;i++)
{
printf("%c \n", cur->fname);
cur=cur->next;
}
return;
}
答案 0 :(得分:3)
快退一步;我想根据您在代码中看到的内容建议一些通用编程指南:
RECORD* insert (RECORD *it)
{
RECORD *cur, *q;
int num;
char junk;
char first[strsize];
printf("Enter a character:");
scanf("%c", &first);
cur=(RECORD *) malloc(sizeof(RECORD));
适用于复杂数据结构的记录上的insert()
例程通常不会被期望/允许/期望执行用户交互;您正在使用内部业务逻辑混合用户界面。 (虽然业务逻辑是一个high-falutin短语,但我不知道更好的方式来说“你的程序必须做的事情,以证明其存在的合理性”或“基本要求”该计划必须满足“。欢迎更换建议。:)
将此伪代码视为替代算法:
while we need more characters
prompt user for another character
store character in datastructure
print datastructure in reverse
将数据结构的所有代码与与人类的交互分开。 (这种表现与逻辑的分离通常被形式化为 Model View Controller,但重要的是要认识到不仅限于用户界面 - 您希望堆栈,列表或队列在 next 编程项目,因此构建仅在堆栈,列表或队列上运行的通用例程,并且可以在下一个项目中重用它们。)
<强>更新强>
编写一个创建链接的程序 10个字符的列表,然后创建一个 以相反的顺序复制列表。该 应提示用户输入 字符和程序应该有 打印出来的打印功能 原始列表然后打印出来 按相反顺序列出
现在这个更像是它。虽然我很欣赏老师想要做的事情,但链接列表并不是我为这个问题选择的数据结构。 (如果问题大小是 bounded ,我会选择一个数组,如果问题大小无限制,则会选择一个堆栈。)它可以通过链表解决,并且有三种可能的方法立即浮现在脑海中:< / p>
编写一个递归输出函数,其工作方式如下:
void print_output(RECORD *r) {
if this is the last RECORD in the chain
print the data
else
print_output(next record in the chain)
}
这使用call stack来反转输出。聪明的伎俩,但与其他方法相比,有时会浪费记忆。
使用双向链接列表元素编写列表。同时使用next
和prev
指针,并仔细管理它们,以便您可以在任一方向上遍历列表。这需要微妙的编码并仔细思考。或者从已发布的源(例如Knuth或您喜欢的算法文本)复制正确的操作顺序。 :)
实际上reverse your singly-linked list。还需要细微,细致的编码或周到的复制。 :)
答案 1 :(得分:1)
在RECORD* print(RECORD *it, int j)
函数中,告诉printf您要打印一个字符,但是您正在将指针传递给fname
数组中的第一个元素,这是一个内存地址。
使用:
printf("%s \n", cur->fname); /* print the string */
或
printf("%c \n", *cur->fname); /* print the first character */
我不确定你想要什么,因为你的问题非常模糊。