我刚刚开始学习C语言中的指针和链接列表,有些事情我还不了解。我试图剪切输入字符串并将该字符串的某些部分分配给一个结构,并将该结构添加到链表的开头,最后进行打印。输入是格式为'a word1 word2 word3
或'l word1 word2 word3'
的字符串。我的问题是,列表的打印方式不像预期的那样,我认为这是因为我向列表中添加元素的方式。我希望它打印3个单词,而只是在最后一个输入字符串中打印最后两个单词。谢谢!
这是我的代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXINPUT 682
typedef struct words{
char * str1;
char * str2;
char * str3;
} words;
typedef struct node{
words data;
struct node * next;
} node;
typedef node * link;
link head; /*head of list*/
/*adds node to list*/
void add(char c[]){
words x;
char * str;
link temp = (link)malloc(sizeof(node));
strtok(c, " ");
str = strtok(NULL," ");
x.str1 = str;
str = strtok(NULL," ");
x.str2 = str;
str = strtok(NULL,"\0");
x.str3 = str;
temp->data = x;
temp->next = head;
head = temp;
}
void print_list(){
link temp;
for (temp = head;temp;temp = temp->next){
printf("%s %s %s\n", temp->cont.nome,temp->cont.email,temp->cont.numero);
}
}
int main(){
char input[MAXINPUT];
head = NULL;
while (input[0] != 'x'){
fgets(input,682,stdin);
input[strcspn(input,"\r\n")] = 0;
if (input[0] == 'a')
add(input);
if (input[0] == 'l')
print_list();
...