gpt4 book ai didi

c - c中如何比较栈和链表的元素?

转载 作者:行者123 更新时间:2023-11-30 15:13:58 24 4
gpt4 key购买 nike

我需要比较来检查元素是否同时在堆栈和链表中。我使用链表实现了堆栈。我在 void 类型中创建了一个名为 search_both 的新方法并尝试进行搜索。

    struct student{
char name[100];
char surname[100];
char roll[10];
char department[50];
struct student *next;
};

struct theStack
{
struct student *head;
struct student *pop;
struct student st;
};

struct theStack myStack;

void search_both()
{
struct student *a;
struct theStack *x;
a=malloc(sizeof *a);
x=malloc(sizeof *x);
if(a&&x)
{
while(strcmp(a->name, x->st.name)==0)
{
while(strcmp (a->surname, x->st.surname)==0)
{
printf("%s %s and %s %s taking both classes",a->name, a->surname,x->st.name,x->st.surname);
a=a->next;
x=x->st.next;
}
}
}
free(a);
free(x);
}

编辑后:我为 a 和 x 变量分配了内存:

 a=(struct student*)malloc(sizeof *a);
x=(struct theStack*)malloc(sizeof *x);

更改后,if 内的第一个循环变得可运行,但另一个 while 循环未执行。在第二个 while 循环中,我试图比较所有姓氏 第二个 while 的错误部分一定是什么?

最佳答案

在分配内存并填充搜索函数外部的结构之后,您根本没有进行迭代:

void search_both( struct student * pStudent, struct theStack * pStack) {
struct sutdent * a = pStudent;
struct theStack * x;
while ( a ) {
x = pStack;
while ( x ) {
if ( strcmp(a->surname,x->st.surname) == 0
&& strcmp(a->name,x->st.name) == 0 )
printf("%s %s and %s %s taking both classes",a->name, a->surname,x->st.name,x->st.surname);
x = x.st->next;
}
a = a->next;
}
}

关于c - c中如何比较栈和链表的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34240050/

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