# 合并两个单链表

## 合并两个单链表

#include <iostream>
#include <cstdlib>
using namespace std;
/*单链表*/
typedef struct LNode
{
int data;
LNode *next;
}*LList;
/*单链表初始化*/
void ListInit(LList &L)
{
L = new LNode;
L->next = NULL;
}
/*建立单链表，添加元素*/
void ListCreate(LList &L,int n,int a[])
{
LList p;
L = new LNode;
L->next = NULL;
for(int i = n-1;i >= 0;i --)
{
p = new LNode;
p->data = a[i];
p->next = L->next;
L->next = p;
}
}
/*遍历输出链表*/
void ListTraverse(LList a)
{
LList p;
cout << "( ";
for(p=a->next;p ;p=p->next)
cout << p->data << " ";
cout << ")" << endl;
}
/*链表交错合并*/
void CommonList(LList &A,LList &B)
{
LList a,b,c;
a = A->next,b = B->next,c = A;
while(a != NULL && b != NULL)
{
//添加链表A的元素
c->next = a;
c = a;
a = a->next;
//添加链表B的元素
c->next = b;
c = b;
b = b->next;
}
if(a != NULL) //如果链表A，a节点后边还有元素，继续加
c->next = a;
if(b != NULL)//如果链表B，b节点后边还有元素，继续加
c->next = b;
delete B;//删除链表B
}
int main()
{
LList A,B,C;
int n;
cout << "请输入链表A大小：" << endl;
cin >> n;
int a[n+1];
cout << "请输入元素" << endl;
for(int i = 0; i < n; i ++)
cin >> a[i];
ListCreate(A,n,a);

int m;
cout << "请输入链表B大小：" << endl;
cin >> m;
int b[m+1];
cout << "请输入元素" << endl;
for(int i = 0; i < m; i ++)
cin >> b[i];
ListCreate(B,m,b);

CommonList(A,B);C = A;
cout << endl <<  "交错合并后的链表为：" << endl;
ListTraverse(C);
return 0;
}

©️2019 CSDN 皮肤主题: 游动-白 设计师: 上身试试