系列文章目录
前言
《数据结构基础》c语言版 第2版,Ellis Horowitz著,朱仲涛译
4.2节,page120,习题6
一、题目描述
令x=(x1,x2,…,xn)和y=(y1,y2,…ym)是两个链表,按数据域的非递减序排列。构造算法归并这两个链表,结果存储在新链表z中,z也按数据域的非递减序排列。在归并过程,表x和表y中的结点一一链到z中,要求不用临时结点。讨论算法的复杂度。
二、c++代码
代码如下:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
typedef struct Node{
int data;
struct Node *link;
}listNode;
listNode* create_list(int length)
{
if(length<1)
{
printf("链表中没有元素!\n");
}
listNode *first = (listNode*)malloc(sizeof(listNode));
first->link = NULL;
listNode *p = first;
int value;
printf("请输入%d个整数:\n",length);
for(int i=1;i<=length;i++)
{
listNode *temp = (listNode*)malloc(sizeof(listNode));
scanf("%d",&value);
temp->data = value;
p->link=temp;
p = temp;
}
p->link = NULL;
return first;
};
listNode* merge_list(listNode *l1,listNode *l2)
{
listNode *new_list = new listNode;
new_list->link = NULL;
listNode *temp = new_list;
listNode *temp1 = l1->link;
listNode *temp2 = l2->link;
while (temp1 && temp2)
{
if(temp1->data < temp2->data)
{
listNode *p = new listNode;
p->data = temp1->data;
temp1 = temp1->link;
temp->link = p;
} else{
listNode *p = new listNode;
p->data = temp2->data;
temp2 = temp2->link;
temp->link = p;
}
temp = temp->link;
}
while (temp1)
{
listNode *p = new listNode;
p->data = temp1->data;
temp->link = p;
temp1 = temp1->link;
temp = temp->link;
}
while (temp2)
{
listNode *p = new listNode;
p->data = temp2->data;
temp->link = p;
temp2 = temp2->link;
temp = temp->link;
}
return new_list;
}
void print_list(listNode* list)
{
listNode *tmp;
tmp = list->link;
if(tmp==NULL) {
printf("链表中没有元素!\n");
return;
}
while (tmp)
{
printf("%2d",tmp->data);
tmp = tmp->link;
}
}
int main() {
listNode *x,*y,*z;
int len1,len2;
printf("输入链表1的长度:");
scanf("%d",&len1);
printf("输入链表2的长度:");
scanf("%d",&len2);
x = create_list(len1);
y = create_list(len2);
z = merge_list(x,y);
printf("合并之后的链表为:\n");
print_list(z);
return 0;
}