/*
*创建两个同类型链表
*链表的值不能有相同的,输入以‘#’结束
*合并两链表,数据域相等的结点只留一个
*/
#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;
}
}
求两链表的并集
最新推荐文章于 2023-03-05 16:28:23 发布