渴望学到知识的菜鸟


私信TA

用户名:ldhskd

访问量:29798

签 名:

这小伙子人行,能处!

等  级
排  名 117
经  验 7608
参赛次数 1
文章发表 48
年  龄 18
在职情况 学生
学  校
专  业

  自我简介:

解题思路:

首先,需要创建一个链表

typedef struct student {
	int id;
	int chengji;
	struct student* next;
}*node, Node;

//一般创建链表我们都用typedef  struct,因为这样定义结构体变量时,
//我们就可以直接可以用node a 来定义结构体指针,Node b来定义结构体变量
//其实就是用 node 代替了struct student * 
//Node 代替了struct student



其次初始化一个链表,n为链表节点个数。

node creat(int n)
{
	node head, p, q;
	head = (node)malloc(sizeof(Node));
	head->next = NULL;
	q = head;
	for (int i = 0; i < n; i++)
	{
		p = (node)malloc(sizeof(Node));
		scanf("%d%d", &(*p).id, &p->chengji);
		p->next = q->next; //这里用的链表的后插法
		q->next = p;
		q = p;
	}
	return head;
}



之后是进行删除

void fun(node h1, node h2)
{
	h2 = h2->next;

	node p, t = h2;
	while (h1->next != NULL)
	{
		h2 = t;
		int flag = 0;
		while (h2 != NULL)
		{
			p = (node)malloc(sizeof(Node));
			if (h1->next->id == h2->id)
			{
				p = h1->next;
				h1->next = p->next;
				free(p);
				flag = 1;
			}
			h2 = h2->next;
		}
		if(flag == 0)    //重点!
		h1 = h1->next;   //重点!
	}
}


这里有一个重点,就是如果进行了删除,是不需要进行指向下一个链表的,

因为h1之前指向的next已经被删除了,现在指向的next应该是之前的next

的next,所以不需要再往后移动了




最后进行打印

void outPut(node h1)
{
	int count = 0;
	node p = h1;
	while (h1 = h1->next) count++;
	printf("%d\n", count);
	p = p->next;
	while (p != NULL)
	{
		printf("%d %d\n", p->id, p->chengji);
		p = p->next;
	}
}




参考代码:

#include <stdio.h>
#include <malloc.h>

typedef struct student {
	int id;
	int chengji;
	struct student* next;
}*node, Node;

node creat(int n)
{
	node head, p, q;
	head = (node)malloc(sizeof(Node));
	head->next = NULL;
	q = head;
	for (int i = 0; i < n; i++)
	{
		p = (node)malloc(sizeof(Node));
		scanf("%d%d", &(*p).id, &p->chengji);
		p->next = q->next;
		q->next = p;
		q = p;
	}
	return head;
}

void fun(node h1, node h2)
{
	h2 = h2->next;

	node p, t = h2;
	while (h1->next != NULL)
	{
		h2 = t;
		int flag = 0;
		while (h2 != NULL)
		{
			p = (node)malloc(sizeof(Node));
			if (h1->next->id == h2->id)
			{
				p = h1->next;
				h1->next = p->next;
				free(p);
				flag = 1;
			}
			h2 = h2->next;
		}
		if(flag == 0)
		h1 = h1->next;
	}
}


void outPut(node h1)
{
	int count = 0;
	node p = h1;
	while (h1 = h1->next) count++;
	printf("%d\n", count);
	p = p->next;
	while (p != NULL)
	{
		printf("%d %d\n", p->id, p->chengji);
		p = p->next;
	}
}


int main()
{
	int m, n;
	node head1, head2;
	scanf("%d%d", &n, &m);
	head1 = creat(n);
	head2 = creat(m);
	fun(head1, head2);
	outPut(head1);
	return 0;
}


 

0.0分

0 人评分

  评论区