我正在学习链表,但现在每次我使用此代码时,我都会在 case1 和 case3 中得到乱码字符

  • 本文关键字:case3 case1 字符 码字 链表 学习 代码 c
  • 更新时间 :
  • 英文 :

#include <stdio.h>
#include <stdlib.h>

struct LLNode
{
char key[10];
struct LLNode *next;
};

struct LLNode *creatNode(char val[10])
{
struct LLNode*temp;
temp=(struct LLNode *)malloc(sizeof(struct LLNode));
temp->key[10]=val;
temp->next=NULL;
return (temp);
};
void push(char val[10], struct LLNode *head)
{
struct LLNode *temp;
temp = creatNode(val[10]);
temp->next = head->next;
head->next = temp;
}


int main()
{
int cho,a=0;
struct LLNode *head=NULL;
struct LLNode *curr=NULL;
head=creatNode('/0');
curr=head;
curr->next = creatNode("Jan");
curr = curr->next;
curr->next = creatNode("Feb");
curr = curr->next;
curr->next = creatNode("Mar");
curr = curr->next;
curr->next = creatNode("Apr");
curr = curr->next;
curr->next = creatNode("May");
curr = curr->next;
curr->next = creatNode("Jun");
curr = curr->next;
curr->next = creatNode("Jul");
curr = curr->next;
curr->next = creatNode("Aug");
curr = curr->next;
curr->next = creatNode("Sep");
curr = curr->next;
curr->next = creatNode("Oct");
curr = curr->next;
curr->next = creatNode("Nov");
curr = curr->next;
curr->next = creatNode("Dec");
curr=head;

printf("1. Create a new node in the linked listn");
printf("2. Search the month of 'May' in the linked listn");
printf("3. Display the content of each noden");
printf("4. Exitn");
printf("nnPlease enter the serial number of your choice:");
scanf("%d",&cho);
switch(cho)
{
case 1:
push ("newnode", head);
printf("head->next->key = %sn",head->next->key) ;
printf("the new node is insert successfully");
break;
case 2:
curr=head;
while(a==0)
{
if(curr->key[10]="May")a=1;
else curr=curr->next;
}
curr=head;
if(a==1) printf("n'May'is in the list.n");
else printf("n'May'is not in the list.n");
break;

case 3:
curr=head;
while(curr)
{

printf("%s  ",curr->key);
curr=curr->next;
}
break;

case 4:
printf("You are exiting");
break;

}
return 0;
}

我正在学习链表,但是现在每次我使用这段代码时,我都会在case1和case3的字符串输出中得到乱码。

此代码的目的是实现图像(在链接中)

中的任务在这里输入图像描述我第一次使用它的时候,我发现我被要求添加更多的语句,所以我在这里复制了一些无意义的东西我第一次使用它的时候,我发现我被要求添加更多的语句,所以我在这里复制了一些无意义的东西我第一次使用它的时候,我发现我被要求添加更多的语句,所以我在这里复制了一些无意义的东西第一次使用它时,我发现我被要求增加一些语句,所以我在这里复制了一些无意义的内容

在情况2中,请注意您没有检查确定curr是否为NULL。如果没有找到"May",这将愉快地循环,直到currNULL,然后您将尝试访问NULL上的成员字段,导致错误。

在情况1中,您同样必须检查head->next是或不是NULL

我建议在第二种情况下,你替换你的while循环如下:

同样在第二种情况下,你有几个错误:

if(curr->key[10]="May")a=1;
  1. 您正在分配curr->key[10].
  2. 你正在分配一个char指针给一个char。
  3. key只保存10个字符。索引从0开始,所以10是越界的。
  4. 如果你试图复制一个字符串,C中的字符串复制不会这样工作。

你对C字符串处理和数组赋值的混淆出现在代码的其他位置。

推荐通过C标签信息页阅读。

最新更新