将两个有序链表合并成一个有序链表
#include <iostream>
#include <string>
using namespace std;
typedef struct LNode
{
int data;//Node data field
struct LNode *next;//Pointer field of the node
}LNode, *LinkList;//linklist is the pointer to LNode;
void createlist_R(LinkList &L){//生成链表
int n;
LinkList s, r;
L = new LNode;
L->next = NULL;//create a linklist with a head;
r = L;
cout << "please input the number of figure" << endl;
cin >> n;
cout << "Please enter non-decreasing integers in order" << endl;
//creat the linklist
while (n--){
s = new LNode;
cin >> s->data;
s->next = NULL;
r->next = s;
r = s;
}
}
void mergelinklist(LinkList La, LinkList Lb, LinkList&Lc){//将两链表整合到Lc中
LinkList p, q, r;
p = La->next;
q = Lb->next;
Lc = La;
r = Lc;
while (p&&q)
{
if (p->data<=q->data)
{
r->next = p;
r = p;
p = p->next;
}
else {
r->next = q;
r = q;
q = q->next;
}
}
r->next = p ? p: q;
delete Lb;
}
void LinkList_L(LinkList L){//输出链表中内容
LinkList P;
P = L->next;
while (P){
cout << P->data << endl;
P = P->next;
}
}
int main(){
int c;
LinkList La, Lb, Lc;
createlist_R(La);//生成链表La
LinkList_L(La);
createlist_R(Lb);//生成链表Lb
LinkList_L(Lb);
mergelinklist(La, Lb, Lc);
LinkList_L(Lc);//输出链表Lc中的内容
cin.get();
return 0;
}