码迷,mamicode.com
首页 > 其他好文 > 详细

两个链表的合并

时间:2016-01-01 13:08:39      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:两个链表的合并

主要功能:

实现两个链表的合并

基本功能要求:

1)建立两个链表AB,链表元个数分别为mn个。

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表(304115125680

B表(235678231233799055

2) A表(304115125680231234

B表(2356782312

代码:

#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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!