#include<stdio.h>
#include<stdlib.h>
typedef struct LNode
{
int data;
struct LNode* next;
}LNode, * LinkList;//LinkList为指向结构体LNode的指针类型
LinkList read()
{
int len = 0;
int num = 0;
LinkList h = NULL;
LinkList Last = NULL;
scanf_s(" %d", &len);
if (len == 0)
return NULL;
h = (LinkList)malloc(sizeof(LNode));
h->next = NULL;
Last = h;
while (len)
{
scanf_s("%d", &num);
LinkList node = (LinkList)malloc(sizeof(LNode));
node->data=num;
node->next = NULL;
Last->next = node;
Last = node;
len--;
}
return h;
}
void Print(LinkList L)
{
if (L->next == NULL)
{
printf("NULL\n");
return;
}
L = L->next;
while (L != NULL)
{
printf("%d--", L->data);
L = L->next;
}
}
LinkList Merge(LinkList L1, LinkList L2)
{
if (!L1 && !L2)
return NULL;
LinkList P1 = L1->next;
LinkList P2 = L2->next;
LinkList L3 = (LinkList)malloc(sizeof(LNode));
//LinkList p3 = new LNode;
L3->next = NULL;
LinkList P3 = L3;
while (P1 && P2)
{
if (P1->data < P2->data)
{
P3->next=P1;
P1 = P1->next;
}
else
{
P3->next = P2;
P2 = P2->next;
}
P3 = P3->next;
}
if (P1)
{
P3->next = P1;
}
if (P2)
{
P3->next = P2;
}
L1->next = NULL;
L2->next = NULL;
return L3;
}
void MergeList_L(LinkList& La, LinkList& Lb, LinkList& Lc)
{
LinkList pa = La->next;
LinkList pb = Lb->next,pc;
pc = Lc = La;
while (pa && pb)
{
if (pa->data <= pb->data)
{
pc->next = pa;
pc = pa;
pa = pa->next;
}
else
{
pc->next = pb;
pc = pa;
pa = pa->next;
}
pc->next = pa ? pa : pb;
}
}
int main()
{
LinkList L1, L2,L;
L1 = read();
L2 = read();
//L = Merge(L1, L2);
MergeList_L(L1, L2, L);
Print(L1);
printf("\n");
Print(L2);
printf("\n");
Print(L);
printf("\n");
return 0;
}
题目二(链表合并)
最新推荐文章于 2024-11-02 19:49:34 发布