#define _CRT_SECURE_NO_WARINING
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define Status int
//初始化链表
typedef struct Lnode {
int data; //数据域
struct Lnode* next; //指针域
}Lnode,*LinkList;
LinkList CreateList_R(LinkList L, int n)
{
int i,data;
L = (LinkList)malloc(sizeof(Lnode));
L->next = NULL;
Lnode* Ptail = NULL;
LinkList Pnew = NULL;
Ptail = L;
printf("请输入%d个数字:\n",n);
for (i = 0; i < n; i++)
{
Pnew = (LinkList)malloc(sizeof(Lnode));
scanf_s("%d", &data);
Pnew->data = data;
Ptail->next = Pnew;
Ptail = Pnew;
}
Pnew->next = NULL;
return L;
}
void Print(LinkList head)
{
Lnode *h = head->next;
if (h ==NULL)
{
printf("The link is NULL");
}
while (h != NULL)
{
printf("%d ", h->data);
h = h->next;
}
}
LinkList match(LinkList P1, LinkList P2, LinkList P3)
{
Lnode* pa=P1->next, * pb=P2->next,*q=P2->next;
P3 = P1;
Lnode* pc = P3;
while (pa && pb)
{
if (pa->data < pb->data)
{
pc->next = pa;
pc = pa;
pa = pa->next;
}
else if(pa->data > pb->data)
{
pc->next = pb;
pc = pb;
pb = pb->next;
}
else { //当元素相等时,取pa的元素,并删除pb的元素
pc->next = pa;
pc = pa;
pa = pa->next;
q = pb->next;//存放pb之后的元素
free(pb);//删除pb的元素
pb = q;//此时pb等于原来相等的元素的下一个元素。
}
}
pc->next = pa ? pa : pb;
free(P2);
return P3;
}
int main()
{
LinkList L1,L2,L3;
int i=0;
L1 = NULL;
L2 = NULL;
L3 = NULL;
L1=CreateList_R(L1, 3);
L2=CreateList_R(L2, 4);
L3 = match(L1, L2,L3);
Print(L3);
return 0;
}
递增合并单链表,无重复元素。
最新推荐文章于 2024-09-05 16:19:52 发布