顺序表的合并
#include <stdio.h>
#include <stdlib.h>
#include<iostream>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE]; // 数据存储区
int length; // 当前长度
} SeqList, * PSeqList;
// 将两个有序表合并成一个有序表
void merge_seq_list(PSeqList list1, PSeqList list2, PSeqList result) {
int i = 0, j = 0, k = 0;
while (i < list1->length && j < list2->length) {
if (list1->data[i] <= list2->data[j]) {
result->data[k++] = list1->data[i++];
}
else {
result->data[k++] = list2->data[j++];
}
}
while (i < list1->length) {
result->data[k++] = list1->data[i++];
}
while (j < list2->length) {
result->data[k++] = list2->data[j++];
}
result->length = k;
}
链表的合并
#include <stdio.h>
#include <stdlib.h>
#define _CRT_SECURE_NO_WARNINGS
//定义链表节点结构体
struct node {
int data;
struct node* next;
};
//定义链表合并函数
struct node* merge(struct node* head1, struct node* head2) {
struct node* p = head1;
while (p->next != NULL) {
p = p->next;
}
p->next = head2;
return head1;
}
//定义创建链表函数
struct node* create() {
int data;
struct node* head, * p, * tail;
head = (struct node*)malloc(sizeof(struct node));
if (head == NULL) {
printf("分配内存失败\n");
exit(1);
}
tail = head;
tail->next = NULL;
printf("请输入节点的数据,输入-1结束:");
int result = scanf_s("%d", &data);
while (data != -1) {
if (result != 1) {
printf("输入错误,请重新输入:");
continue;
}
p = (struct node*)malloc(sizeof(struct node));
if (p == NULL) {
printf("分配内存失败\n");
exit(1);
}
p->data = data;
tail->next = p;
tail = p;
tail->next = NULL;
printf("请输入节点的数据,输入-1结束:");
result = scanf_s("%d", &data);
}
return head;
}
//定义遍历链表函数
void traverse(struct node* head) {
struct node* p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
struct node* head1, * head2, * head3;
//创建链表1
printf("创建链表1:\n");
head1 = create();
printf("链表1的元素为:");
traverse(head1);
//创建链表2
printf("创建链表2:\n");
head2 = create();
printf("链表2的元素为:");
traverse(head2);
//合并链表
printf("合并链表1和链表2:\n");
head3 = merge(head1, head2);
printf("合并后的链表元素为:");
traverse(head3);
return 0;
}