算法描述:已知两个递增的单链表,将这两个单链表归并,得到一个非递减的单链表
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
typedef struct LNode
{
int data;
struct LNode* next;
}LNode;
int main()
{
void createlist(LNode*&, int);
void mergelist(LNode*, LNode*, LNode*&);
void printlist(LNode*);
LNode* a, * b, * c;
int n1, n2;
cout << "Please enter the length of the first linked list:";
cin >> n1;
createlist(a, n1);
printlist(a);
cout << "Please enter the length of the second linked list:";
cin >> n2;
createlist(b, n2);
printlist(b);
mergelist(a, b, c);
printlist(c);
return 0;
}
void createlist(LNode*& a, int n)
{
LNode* p;
a = (LNode*)malloc(sizeof(LNode));
p = (LNode*)malloc(sizeof(LNode));
a->next = p;
cout << "Please enter the elements of the linked list one by one in an increasing order:";
for (int i = 0; i < n; i++)
{
cin >> p->data;
if (i < n - 1)
{
p->next = (LNode*)malloc(sizeof(LNode));
p = p->next;
}
}
p->next = NULL;
return;
}
void mergelist(LNode* a, LNode* b, LNode*& c)
{
LNode* p;
c = (LNode*)malloc(sizeof(LNode));
p = (LNode*)malloc(sizeof(LNode));
c->next = p;
a = a->next;
b = b->next;
while (a != NULL || b != NULL)
{
if (a == NULL)
{
p->data = b->data;
b = b->next;
}
else
{
if (b == NULL)
{
p->data = a->data;
a = a->next;
}
else
{
if (a->data < b->data)
{
p->data = a->data;
a = a->next;
}
else
{
p->data = b->data;
b = b->next;
}
}
}
if (a != NULL || b != NULL)
{
p->next= (LNode*)malloc(sizeof(LNode));
p = p->next;
}
}
p->next = NULL;
return;
}
void printlist(LNode* a)
{
a = a->next;
while (a)
{
cout << a->data;
if (a->next)
{
cout << " -> ";
}
a = a->next;
}
cout << endl;
return;
}
运行结果:
Please enter the length of the first linked list:8
Please enter the elements of the linked list one by one in an increasing order:2 3 5 9 10 15 18 21
2 -> 3 -> 5 -> 9 -> 10 -> 15 -> 18 -> 21
Please enter the length of the second linked list:8
Please enter the elements of the linked list one by one in an increasing order:5 8 9 10 13 15 19 20
5 -> 8 -> 9 -> 10 -> 13 -> 15 -> 19 -> 20
2 -> 3 -> 5 -> 5 -> 8 -> 9 -> 9 -> 10 -> 10 -> 13 -> 15 -> 15 -> 18 -> 19 -> 20 -> 21