双链表的合并
#include<stdio.h>
#include<stdlib.h>
typedef struct NODE {
int data;
struct NODE* Pnext;
}NODE,*PNODE;
void init_list(PNODE &pHead,int n);
void traver_list(PNODE pHead);
PNODE merge_list(PNODE pHead1, PNODE pHead2);
void init(PNODE& pHead, int n);
int main() {
PNODE pHead1, pHead2,pHead3;
init(pHead1,1);
init(pHead2,2);
traver_list(pHead1);
traver_list(pHead2);
pHead3 = merge_list(pHead1, pHead2);
printf("合并后的链表:");
traver_list(pHead3);
}
void init_list(PNODE& pHead, int n) {
pHead = new NODE;
if (pHead == nullptr) {
printf("内存分配失败!程序退出!");
exit(-1);
}
pHead->Pnext = NULL;
if (n == 1) {
for (int i = 1; i <= 5; i++) {
PNODE pNew = new NODE;
pNew->data = 2 * i - 1;
pNew->Pnext = pHead->Pnext;
pHead->Pnext = pNew;
}
}
else if (n == 2) {
for (int i = 1; i <= 5; i++)
{
PNODE pNew = new NODE;
pNew->data = 2 * i;
pNew->Pnext = pHead->Pnext;
pHead->Pnext = pNew;
}
}
}
void traver_list(PNODE pHead) {
PNODE p = pHead->Pnext;
while (p != NULL) {
printf("%3d",p->data);
p = p->Pnext;
}
putchar('\n');
}
PNODE merge_list(PNODE pHead1, PNODE pHead2) {
PNODE pHead3 = new NODE;
PNODE p1, p2,p3;
p3 = pHead3;
p1 = pHead1->Pnext;
p2 = pHead2->Pnext;
while (p1 !=NULL && p2 !=NULL) {
if (p1->data > p2->data) {
p3->Pnext = p2;
p2 = p2->Pnext;
}
else{
p3->Pnext = p1;
p1 = p1->Pnext;
}
p3 = p3->Pnext;
}
if (p1 == NULL) {
p3->Pnext = p2;
}
if (p2 == NULL) {
p3->Pnext = p1;
}
return pHead3;
}
void init(PNODE& pHead, int n) {
pHead = new NODE;
if (pHead == nullptr) {
printf("内存分配失败!程序退出!");
exit(-1);
}
PNODE pTaile;
pTaile = pHead;
pTaile->Pnext = NULL;
if(n==1)
for (int i = 1; i <= 5; i++) {
PNODE pNew = new NODE;
pNew->data = 2 * i - 1;
pNew->Pnext =NULL;
pTaile->Pnext = pNew;
pTaile = pNew;
}
else if(n==2) {
for (int i = 1; i <= 5; i++) {
PNODE pNew = new NODE;
pNew->data = 2 * i;
pNew->Pnext = NULL;
pTaile->Pnext = pNew;
pTaile=pNew ;
}
}
}