求两链表的并集

/*
*创建两个同类型链表
*链表的值不能有相同的,输入以‘#’结束
*合并两链表,数据域相等的结点只留一个
*/

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

typedef struct node
{
	char data;
	struct node* next;
}*Node;

Node CreateList(int);					//初始化链表
bool judge(char ch,Node head);			//判断链表中是否已经有该数据
void printList(Node head);				//打印链表	
bool isNotExist(char ch,Node head);		//判断2号链表中结点的数据域是否与1号链表中的结点存在相等的
void createNewList(Node L1,Node L2);	//合并两链表	

int main(void)
{
	Node pHead1 = NULL;
	Node pHead2 = NULL;
	Node pNew = NULL;
	pHead1 = CreateList(1);
	pHead2 = CreateList(2);
//	printList(pHead1);
//	printList(pHead2);

//	printf("到了");
	createNewList(pHead1,pHead2);
//	printf("到了");
	printList(pHead1);
	return 0;
}

void createNewList(Node L1,Node L2)
{
	Node temp1 = L1;
	Node temp2 = L2->next;
	Node head = NULL,relea = NULL,head_temp = NULL;
	while(temp1!=NULL)
	{
		head = temp1;
		temp1 = temp1->next;
	}
	while(L2!=NULL)
	{
		if(isNotExist(L2->data,L1))
		{
			head_temp = (Node)malloc(sizeof(node));
			head_temp->data = L2->data;
			head_temp->next = NULL;
			head->next = head_temp;
			head = head_temp;
		}
		L2 = L2->next;
	}
	//释放链表2空间
	while(temp2!=NULL)
	{
		relea=temp2->next;
		free(temp2);
		temp2=relea;
	}
	free(relea),free(temp2);
}

bool isNotExist(char ch,Node head)
{
	while(head!=NULL)
	{
		if(head->data == ch)
			return false;
		head = head->next;
	}
	return true;
}


Node CreateList(int i)
{
	Node L = (Node)malloc(sizeof(node));
	L->next = NULL;
	Node p = L;
	char ch;
	printf("初始化链表,输入字符,以'#'结束输入\n");
	printf("node %d\n",i);
	while((ch = getchar())!='#')			//这里没进去
	{
		if(judge(ch,L))
			continue;
		Node pNew = (Node)malloc(sizeof(node));
		pNew->data = ch;
		pNew->next = NULL;
		p->next = pNew;
		p = pNew;
		getchar();
	}
	while((ch = getchar())!='\n')
		continue;
	return L;
}

bool judge(char ch,Node head)
{
	Node r = head->next;
	while(r!=NULL)
	{	
		if(ch == r->data)
		{
			printf("字符已经存在,请重新输入\n");
			getchar();
			return true;
		}
		r = r->next;
	}
	return false;
}

void printList(Node head)
{
	Node p = head->next;
	int i = 1;
	while(p!=NULL)
	{
		printf("结点%d   data = %c\n",i++,p->data);
		p = p->next;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值