题目:
代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct SList
{
int data;
struct SList* next;
}SL;
void SLInit(SL** ps)
{
*ps = (SL*)malloc(sizeof(SL));
(*ps)->next = NULL;
}
void SLCreate(SL** ps, int n)
{
SL* cur = *ps;
int x = 0;
while (n--)
{
scanf("%d", &x);
getchar();
SL* newnode = (SL*)malloc(sizeof(SL));
newnode->data = x;
cur->next = newnode;
cur = newnode;
}
cur->next = NULL;
}
void SLCombine(SL** psA, SL** psB)
{
SL* beginB = (*psB)->next;
SL* endA = (*psA)->next;
while (endA->next)//去找A链表的尾节点
{
endA = endA->next;
}
while (beginB)//B链表为空时结束
{
int flag = 0;//每次用flag记录一下
SL* beginA = (*psA)->next;//每一次循环都把A放在首位
while (beginA)
{
if (beginB->data == beginA->data)
{
flag = 1;//在A链表中找到和B相等的数
break;
}
beginA = beginA->next;//beginA向后迭代
}
if (flag == 1)//等于1时结束程序说明是因为找到相等的数结束
{
beginB = beginB->next;//beginB向后迭代
}
else//flag=0时说明是beginA走到尾节点时结束的上面的while循环,需要把这个数链接在后面
{
SL* newnode = (SL*)malloc(sizeof(SL));
newnode->data = beginB->data;
endA->next = newnode;
endA = newnode;
endA->next = NULL;
beginB = beginB->next;//beginB向后迭代
}
}
}
void SLPrint(SL** ps)
{
SL* cur = (*ps)->next;
while (cur != NULL)
{
printf("%d ", cur->data);
cur = cur->next;
}
}
int main()
{
SL* LA=NULL;
SLInit(&LA);
SL* LB = NULL;
SLInit(&LB);
int n = 0;
scanf("%d", &n);
getchar();
SLCreate(&LA, n);
int m = 0;
scanf("%d", &m);
getchar();
SLCreate(&LB, m);
SLCombine(&LA, &LB);
SLPrint(&LA);
return 0;
}