有两个链表a和b,设结点中包含学号、姓名。从a链表中删去与b链表中有相同学号的那些结点。
【输入说明】
输入第一行两个整数,分别表示链表a的节点数量n和链表b的节点数量m。接下来有n + m行数据,
每行数据包括学号,姓名,分别用空格间隔。
【输出说明】
如果链表为空 则输出:链表为空
【输入样例】
3 2
101 zhangsan
102 wangwu
103 lisi
102 wangwu
103 lisi
【输出样例】
101 zhangsan
#include <stdio.h>
#include<stdlib.h>
struct student
{
int num;
char name[10];
struct student* next;
};
struct student* create(int n);//创建n个节点
struct student* solve(struct student* head_a, struct student* head_b);//删除相同的节点
void print(struct student*head); //打印
int main()
{
int n, m;
printf("链表a的节点数 链表b的节点数\n");
scanf("%d %d", &n, &m);
printf("给链表a赋值\n");
struct student* list_A = create(n);
printf("给链表b赋值\n");
struct student* list_B = create(m);
printf("打印删除相同元素后的链表a\n");
struct student* list_C = solve(list_A, list_B);
if (list_C == NULL)
printf("链表为空");
else
print(list_C);
return(0);
}
struct student* create(int n)//创建n个节点 并赋值
{
struct student* headnode = (struct student*)malloc(sizeof(struct student));
struct student* pmove = (struct student*)malloc(sizeof(struct student));
headnode->next = NULL;
pmove = headnode;
for (int i = 0; i < n; i++)
{
struct student* newnode = (struct student*)malloc(sizeof(struct student));
pmove->next = newnode;
newnode->next = NULL;
pmove = pmove->next;
}
pmove = headnode;
while (pmove->next)
{
scanf("%d%s", &pmove->num, &pmove->name);
pmove = pmove->next;
}
return headnode;
}
void print(struct student* head) //打印
{
struct student* pmove = (struct student*)malloc(sizeof(struct student));
pmove = head;
while (pmove)
{
printf("%d %s\n", pmove->num, pmove->name);
pmove = pmove->next;
}
}
struct student* solve(struct student* head_a, struct student* head_b)//删除相同的节点
{
struct student* pmove_a = (struct student*)malloc(sizeof(struct student));
pmove_a = head_a;
struct student* pmove_b = (struct student*)malloc(sizeof(struct student));
while (pmove_a)//遍历list_a
{
pmove_b = head_b; //每次循环 从头开始遍历b
while (pmove_b)//遍历list_b;
{
if (pmove_a->num == pmove_b->num)//如果a=b
{
if (head_a->num == pmove_b->num)//如果是头删
{
head_a = pmove_a->next;
break;
}
else //中间删 尾删
{
struct student* pmove_c = (struct student*)malloc(sizeof(struct student));
pmove_c = head_a;
while (pmove_c->next != pmove_a)
{
pmove_c = pmove_c->next;
}
pmove_c->next = pmove_a->next;
break;
}
}
pmove_b = pmove_b->next;// 从前往后依次对比 看是否符合上面条件
}
pmove_a = pmove_a->next; // 从前往后依次对比 看是否符合上面条件
}
free(pmove_a);
free(pmove_b);
return head_a;
}