C 带字符串的双链表
我试图通过输入字符串在C中建立一个双链接列表,我想弄清楚我是否正确。这对我来说很难解释,所以我会把我的东西贴出来。我是C的新手,所以请纠正我,我希望我是对的,请让我知道是否最好发布我的全部代码 好的,我有我的指纹,看起来像这样:C 带字符串的双链表,c,C,我试图通过输入字符串在C中建立一个双链接列表,我想弄清楚我是否正确。这对我来说很难解释,所以我会把我的东西贴出来。我是C的新手,所以请纠正我,我希望我是对的,请让我知道是否最好发布我的全部代码 好的,我有我的指纹,看起来像这样: struct node { char data[100]; struct node *previous; // Points to the previous node struct node *next; // Points out to th
struct node
{
char data[100];
struct node *previous; // Points to the previous node
struct node *next; // Points out to the next node
}*head, *last;
这是一个要在开头插入的函数:
void insert_beginning(char words[100])
{
struct node *var, *temp;
var=(struct node *)malloc(sizeof(struct node));
var->data[100]=words[100];
if (head==NULL)
{
head=var;
head->previous=NULL;
head->next=NULL;
last=head;
}
else
{
temp=var;
temp->previous=NULL;
temp->next=head;
head->previous=temp;
head=temp;
}
}
这是我的主要观点:
int main()
{
char words[100];
int i;
head=NULL;
printf("Select the choice of operation on link list");
printf("\n1.) insert at begining\n2.) insert at at\n3.) insert at middle");
printf("\n4.) delete from end\n5.) reverse the link list\n6.) display list\n7.)exit");
while(1)
{
printf("\n\n Enter the choice of operation you want to do ");
scanf("%d",&i);
switch(i)
{
case 1:
{
printf("Enter the value you want to insert in node ");
scanf(" %s",&words);
insert_beginning(words);
display();
break;
}
我只是想确定这三个部分是否正确。我错过什么了吗?
谢谢你的帮助。我希望我没有使任何事情复杂化,并根据需要提出了问题。您的函数
insert\u start
有问题:
var=(struct node *)malloc(sizeof(struct node));
var->data[100]=words[100]
通过这两行,您可以复制单词
数组,并将其放在列表的节点上:)
但是如果实现为false,只需将第100个字符
从单词
数组复制到节点数据
第100个字符,这超出了数组的范围,因为第一个字符从0开始,最后一个字符在99索引处
您必须复制所有单词
内容,因此您可以使用strncpy
功能执行此操作:
strncpy(var->data, words, 100);
因此,您的函数将如下所示:
void insert_beginning(char words[100])
{
struct node *var, *temp;
var=(struct node *)malloc(sizeof(struct node));
strncpy(var->data, words, 100);
if (head==NULL)
{
head=var;
head->previous=NULL;
head->next=NULL;
last=head;
}
else
{
temp=var;
temp->previous=NULL;
temp->next=head;
head->previous=temp;
head=temp;
}
}
不要使用strcpy
因为z不是防止缓冲区溢出的安全函数,请使用strncpy
它留给你的只是修复我不明白你想做什么的主要问题。你希望通过
var->data[100]=words[100]实现什么代码>?要复制标准C字符串,请使用strcpy或其更安全的brostrncpy
!如果可能的话,我希望能够插入一些名称甚至短语这是一个代码检查。我认为这类问题比in(不确定)//Bad:var->data[100]=words[100]更好代码>/更好:strcpy(var->data,words);`。谢谢你的回答!你们介意我发布一个新问题吗?这是我问题的第二部分?