输入数据后我想以输入字母的方式结束,但是char无法转换int,请问该如何修改并且代码怎么样能简化一下
:两个集合A和集合B,要求设计生成集合C=A∩B的算法,其中集合A、B和C用链式存储结构表示
#include
#include
typedef int ElemType;
typedef struct Lnode
{
ElemType date;
struct Lnode* next;
}*LNode;
LNode InitLnode(void) //初始化链表
{
LNode L;
L = (LNode)malloc(sizeof(struct Lnode));
if(L == NULL)
exit(1);
L->next = NULL;
return L;
}
/*尾插入元素*/
void Insert(LNode head,ElemType x)
{
struct Lnode *p,*q;
p = head;
q = (LNode)malloc(sizeof(struct Lnode));
if(!q)
{
printf("Out of space\n");
exit(1);
}
q->date = x;
q->next = NULL;
while(p->next != NULL) //带头结点的链表
{
p = p->next;
}
p->next = q;
}
/*输出链表*/
void Print(LNode head)
{
LNode p;
p = head->next;
while(p!=NULL)
{
printf("%d ",p->date);
p = p->next;
}
}
int IfHas(LNode L,ElemType x)
{
LNode p = L->next;
if(!L)
exit(1);
while(p)
{
if(p->date == x)
return 1;
p = p->next;
}
return 0;
}
void REORDER(LNode LA,LNode LB,LNode LC)
{
LNode p;
p = LA->next;
while(p)
{
if(IfHas(LB,p->date))
Insert(LC,p->date);
p = p->next;
}
}
int main(void)
{
LNode LA,LB,LC;
LA = InitLnode();
LB = InitLnode();
LC = InitLnode();
ElemType N;
printf("输入你要放入链表LA中的数据,输入为end是代表输入结束\n");
while(scanf("%d",&N)!=EOF)
{
if(N == "end" )
break;
Insert(LA,N);
}
printf("输入你要放入链表LB中的数据,输入为end是代表输入结束\n");
while(scanf("%d",&N)!=EOF)
{
if(N == "end" )
break;
Insert(LB,N);
}
printf("LA,LB分别为:\nLA:");
Print(LA);
printf("\nLB:");
Print(LB);
REORDER(LA,LB,LC);
printf("\nLC:");
Print(LC);
printf("\n");
return 0;
}
用%s接收输入内容,先判断是否为end,如果是则结束输入,如果不是则将字符串转换为整型,加个函数就行了
int ToInt(char *s)
{
int n=0,i=0;
while(s[i] != 0)
{
n = n*10 + s[i] - '0';
i++;
}
return n;
}
int main(void)
{
LNode LA,LB,LC;
LA = InitLnode();
LB = InitLnode();
LC = InitLnode();
char s[100];
printf("输入你要放入链表LA中的数据,输入为end是代表输入结束\n");
scanf("%s",s);
while(strcmp(s,"end") != 0)
{
Insert(LA,ToInt(s));
scanf("%s",s);
}
printf("输入你要放入链表LB中的数据,输入为end是代表输入结束\n");
scanf("%s",s);
while(strcmp(s,"end") != 0)
{
Insert(LB,ToInt(s));
scanf("%s",s);
}
printf("LA,LB分别为:\nLA:");
Print(LA);
printf("\nLB:");
Print(LB);
REORDER(LA,LB,LC);
printf("\nLC:");
Print(LC);
printf("\n");
return 0;
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!