有两个链表a和b,设结点中包含学号、姓名。从a链表中删去与b链表中有相同学号的那些结点

有两个链表a和b,设结点中包含学号、姓名。从a链表中删去与b链表中有相同学号的那些结点

解题思路:

对于b链表中的每一个节点,都从a链表的表头开始查找,如果可以找到,直接删除,如果找不到,继续从a链表表头找下一个b的节点。

#include <stdio.h>
typedef struct student
{
	int num;
	double grade;
	struct student *next;
} student;
student *del(student *a, student *b)
{
	student *pre, *current, *head;
	head = a;

	while (b != NULL)
	{
		//重置指针指向a链表的头部
		pre = head;
		current = head->next;
		//a 链表的头等于b
		if (pre->num == b->num)
		{
			pre->next = NULL;
			pre = current;
			current = current->next;
			//更新表头
			head = pre;
		}
		else
		{
			while (pre->next != NULL)
			{
				if (current->num == b->num)
				{
					//找到就删除
					pre->next = current->next;
					break;
				}
				else
				{
					//否则继续遍历
					pre = pre->next;
					current = current->next;
				}
			}
		}
		b = b->next;
	}
	return head;
}

void printList(student *root)
{
	printf("----n");
	int i = 0;
	while (root != NULL)
	{
		printf("student %d -> %d -> %.2lfn", i, root->num, root->grade);
		root = root->next;
		i++;
	}
}

int main()
{
	student a[3] = { { 1, 79 }, { 4, 36 }, { 5, 79 } };
	for (int i = 0; i < 2; i++)
	{
		a[i].next = &a[i + 1];
	}
	a[2].next = NULL;
	printf("链表a:n");
	printList(&a[0]);

	student b[2] = { { 5, 38 }, { 4, 98 } };
	for (int i = 0; i < 1; i++)
	{
		b[i].next = &b[i + 1];
	}
	b[1].next = NULL;
	printf("链表b:n");
	printList(&b[0]);
	student *combine = del(a, b);
	printf("删除之后:n");
	while (combine != NULL)
	{
		printf("%d -> %.2lfn", combine->num, combine->grade);
		combine = combine->next;
	}

	return 0;
}

运行截图:
有两个链表a和b,设结点中包含学号、姓名。从a链表中删去与b链表中有相同学号的那些结点

原文链接: https://www.cnblogs.com/cyuyanchengxu/p/13470585.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    有两个链表a和b,设结点中包含学号、姓名。从a链表中删去与b链表中有相同学号的那些结点

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/201331

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午8:45
下一篇 2023年2月12日 下午8:45

相关推荐