C语言两个升序递增链表逆序合并为一个降序递减链表,并去除重复元素

#include"stdafx.h"
#include<stdlib.h>
#define LEN sizeof(struct student)
 
struct student 
{
	int num;
	struct student *next;
};
int n;
struct student *line(void) //生成链表
{
	struct student *head;
	struct student *p1, *p2;
	n = 0;
	p1 = p2 = (struct student*)malloc(LEN);
	scanf_s("%d", &p1->num);
	head = NULL;
	while (p1->num)
	{
		n++;
		if (n == 1)
			head = p1;
		else
			p2->next = p1;
		p2 = p1;
		p1 = (struct student*)malloc(LEN);
		scanf_s("%d", &p1->num);
	}
	p2->next = NULL;
	return head;
}
//把两个递增的链表合并为一个递减的链表,并去除重复元素。
int main()
{
	struct student *aaa(struct student  *A, struct student  *B);
	struct student *pa, *pb;
	pa = line();
	pb = line();
	aaa(pa, pb);
	return 0;
}
struct student *aaa(struct student  *pa, struct student  *pb)
{
	struct student *pc;
	struct student *p, *q, *s;
	pc = pa;
	pa = pa->next;  pb = pb->next;
	pc->next = NULL;   
	while (pa && pb)//逆序排列
	{
		if (pa->num <= pb->num)
		{
			s = pa; pa = pa->next;
		}
		else
		{
			s = pb; pb = pb->next;
		}
		s->next = pc->next;
		pc->next = s;
	}   
	if (pa == NULL) 
		pa = pb;
	while (pa)
	{
		s = pa; pa = pa->next;
		s->next = pc->next;
		pc->next = s;
	}
	p = pc;
	while (p->next)//去重
	{
		q = p;
		while (q->next)				
		{
			if (q->next->num == p->num)	
			{
				s = q->next;
				q->next = s->next;
				free(s);
			}
			else q = q->next;
		}
		p = p->next;
	}
	while (pc)//输出节点
	{	pc = pc->next;
		printf("%d", pc->num);
		
	}
	return 0;
}
//输入pa和pb的第一个元素会被忽略。
//原因:输入的第一个数字被设为头结点,所以没有参与排序。
posted @ 2022-06-08 19:42  CJK'sBLOG  阅读(106)  评论(0编辑  收藏  举报