标签:两个链表的合并
主要功能:
实现两个链表的合并
基本功能要求:
(1)建立两个链表A和B,链表元素个数分别为m和n个。
(2)假设元素分别为(x1,x2,…xm),和(y1,y2, …yn)。把它们合并成一个线性表C,使得:
当m>=n时,C=x1,y1,x2,y2,…xn,yn,…,xm
当n>m时,C=y1,x1,y2,x2,…ym,xm,…,yn
输出线性表C:
测试数据:
1) A表(30,41,15,12,56,80)
B表(23,56,78,23,12,33,79,90,55)
2) A表(30,41,15,12,56,80,23,12,34)
B表(23,56,78,23,12)
代码:
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
typedef int DataType;
typedef struct Node
{
DataType data;
struct Node *next;
}Node, *LinkList;
//初始化
void InitList(LinkList &head)
{
head = (LinkList)malloc(sizeof(Node));
head->next = NULL;
}
//输出链表
void Print(LinkList head)
{
head = head->next;
while (head != NULL)
{
printf("%d", head->data);
if (head->next != NULL)
{
printf("->");
}
head = head->next;
}
}
//尾插建链表
void CreateFromTail(LinkList &head)
{
DataType val = 0;
Node *r = head;
do{
scanf("%d", &val);
if (val != 0)
{
Node *s = (Node *)malloc(sizeof(Node));
s->data = val;
r->next = s;
r = s;
}
else
{
r->next = NULL;
}
} while (val != 0);
}/*CreateFromTail*/
//求长度
int LinkListLength(LinkList head)
{
Node *LA = head;
int len = 0;
head = head->next;
while (head != NULL)
{
len++;
head = head->next;
}
return len;
}/*LinkListLength*/
void Merge(LinkList headA, LinkList headB, LinkList &headC)
{
int count = 0;
while (headB)
{
Node *s = (Node *)malloc(sizeof(Node));
if (count % 2 == 0)
{
s->data = headA->data;
headC->next = s;
headA = headA->next;
}
else
{
s->data = headB->data;
headC->next = s;
headB = headB->next;
}
headC = headC->next;
count++;
}
while (headA)
{
Node *s = (Node *)malloc(sizeof(Node));
s->data = headA->data;
headC->next = s;
headC = headC->next;
headA = headA->next;
}
headC->next = NULL;
}/*Merge*/
//合并链表
void MerLinkList(LinkList headA, LinkList headB, LinkList &headC)
{
Node *LA = headA->next;
Node *LB = headB->next;
Node *LC = headC;
int lenA = LinkListLength(LA);
int lenB = LinkListLength(LB);
if (lenA >= lenB)
{
Merge(LA, LB, LC);
}/*if (lenA >= lenB)*/
else
{
Merge(LB, LA, LC);
}
}/*MerLinkList*/
int main()
{
LinkList headA;
LinkList headB;
LinkList headC;
//初始化
InitList(headA);
InitList(headB);
InitList(headC);
//尾差法建立链表
//建headA
printf("请输入headA的元素,以0符结束:> ");
CreateFromTail(headA);
printf("\n");
//建headB
printf("请输入headB的元素,以0符结束:> ");
CreateFromTail(headB);
printf("\n");
//合并A,B
MerLinkList(headA, headB, headC);
//输出A,B,C
printf("A链表为:> ");
Print(headA);
printf("\n");
printf("B链表为:> ");
Print(headB);
printf("\n");
printf("C链表为:> ");
Print(headC);
printf("\n");
system("pause");
return 0;
}
测试用例:
标签:两个链表的合并
原文地址:http://10740026.blog.51cto.com/10730026/1730619