最近在帮大一的小学弟做数据结构的课设,感觉这个题目呀比较有意思,就发出来了。
#include <stdio.h>
#include <stdlib.h>
#define true 1
#define false 0
typedef struct Node
{
int data;
struct Node* next;
}LNode;
//函数声明部分
void addList(LNode*, LNode*, LNode*); //链表并集
LNode* createList(); //创建链表
void insertAfterLastNode(LNode*, int); //插入节点
int isExist(int, LNode*); //判断元素是否存在在某个链表中
void listASubtractListB(LNode*, LNode*, LNode*); //链表差集
void mixList(LNode*, LNode*, LNode*); //链表交集
void outputList(LNode*); //输出链表
/*
函数名称:LNode* createList();
函数功能:创建链表
返回值说明:返回创建成功链表的头结点
*/
LNode* createList()
{
int countOfNumber;
LNode* tempL;
LNode* L = (LNode*)malloc(sizeof(LNode));
if (!L)
{
printf("申请空间失败,程序退出!\n");
exit(-1);
}
tempL = L;
printf("请输入数据个数:");
scanf("%d", &countOfNumber);
for (int i = 0; i < countOfNumber; ++i)
{
LNode* S = (LNode*)malloc(sizeof(LNode));
if (!S)
{
printf("临时内存空间申请失败,程序退出!\n");
exit(-1);
}
printf("输入数据:");
scanf("%d", &S->data);
S->next = NULL;
tempL->next = S;
tempL = S;
}
if (countOfNumber == 0)
{
tempL->next = NULL;
}
if (L->next)
{
tempL->next = NULL;
}
return L;
}
void insertAfterLastNode(LNode* L, int insertMember)
{
LNode* tempL = L; //暂存传过来的L节点
LNode* temp = (LNode*)malloc(sizeof(LNode));
temp->data = insertMember;
temp->next = NULL;
//因为题目需要 插入只需要在在最后一个节点处进行即可 所以我们找到最后一个节点的办法就是一直后移直到指针域为空的节点
while (tempL->next)
{
tempL = tempL->next;
}
tempL->next = temp;
}
/*
函数名称:void outputList(LNode*);
函数功能:输出链表
函数返回值:无返回值
*/
void outputList(LNode* L)
{
LNode *tempL = L;
tempL = tempL->next;
while (tempL)
{
printf("%d ", tempL->data);
tempL = tempL->next;
}
}
/*
函数名称:void addList(LNode*, LNode*, LNode*);
函数功能:实现链表的并集
返回值说明:无返回值
*/
void addList(LNode* L1, LNode* L2, LNode* L3)
{
LNode* tempL1 = L1->next;
LNode* tempL2 = L2->next;
//LNode* tempL3 = L3->next;
while (tempL1)
{
if (!isExist(tempL1->data, L3))
{
insertAfterLastNode(L3, tempL1->data);
}
tempL1 = tempL1->next;
}
while (tempL2)
{
if (!isExist(tempL2->data, L3))
{
insertAfterLastNode(L3, tempL2->data);
}
tempL2 = tempL2->next;
}
}
/*
函数名称:void mixList(LNode*, LNode*, LNode*);
函数功能:实现链表交集
返回值说明:无返回值
*/
void mixList(LNode* L1, LNode* L2, LNode* L3)
{
LNode* tempL1 = L1->next;
LNode* tempL2 = L2->next;
while (tempL1)
{
if (isExist(tempL1->data, L2))
{
insertAfterLastNode(L3, tempL1->data);
}
tempL1 = tempL1->next;
}
}
/*
函数名称:void listASubtractListB(LNode*, LNode*, LNode*);
函数功能:实现链表差集
返回值说明:无返回值
*/
void listASubtractListB(LNode* L1, LNode* L2, LNode* L3)
{
LNode* tempL1 = L1->next;
LNode* tempL2 = L2->next;
while (tempL1)
{
if (!isExist(tempL1->data, L2))
{
insertAfterLastNode(L3, tempL1->data);
}
tempL1 = tempL1->next;
}
}
/*
函数名称:int isExist(int, LNode*);
函数功能:查找是否有重复项
返回值说明:如果该链表中存在该元素member,返回true;否则返回false
*/
int isExist(int member, LNode* L)
{
LNode* tempL = L;
while (tempL)
{
if (member == tempL->data)
{
return true;
}
tempL = tempL->next;
}
return false;
}
int main()
{
LNode* L1 = createList();
LNode* L2 = createList();
LNode* L3 = createList();
listASubtractListB(L1, L2, L3);
outputList(L3);
return 0;
}
end