关注公众号程序猿从入门到入土查询更方便哦
1、将两个递增的有序链表合并为一个递增的有序链表。要求结果链表仍使用原来两个链表的存储空间,不另外占用其他的存储空间,表中不允许有重复的数据
#include<iostream>
#include<Windows.h>
#define RESULT int
#define OK 1
#define ERROR 0
using namespace std;
typedef struct Node {
int data;
Node *next;
}LNode, *LinkList;
RESULT InitList(LinkList &L); //初始化链表
RESULT InsertData_Head(LinkList &L, int data); //头插
RESULT InsertData_Back(LinkList &L, int data); //尾插
RESULT InsertData_Middle(LinkList &L, int NO, int data); //在NO位置插入元素
RESULT Output_LinkList(LinkList& L); //打印链表
LinkList List_Combine(LinkList& L_1, LinkList& L_2); //合并链表,仅原空间
int main() {
//初始化链表L_1
LinkList L_1;
if (!InitList(L_1)) {
return 0;
}
InsertData_Back(L_1, 3);
InsertData_Back(L_1, 4);
InsertData_Back(L_1, 5);
InsertData_Back(L_1, 6);
InsertData_Back(L_1, 7);
Output_LinkList(L_1);
//初始化链表L_2
LinkList L_2;
if (!InitList(L_2)) {
return 0;
}
InsertData_Back(L_2, 4);
InsertData_Back(L_2, 6);
InsertData_Back(L_2, 8);
InsertData_Back(L_2, 9);
InsertData_Back(L_2, 14);
Output_LinkList(L_2);
LinkList L_3 = new LNode;
L_3 = List_Combine(L_1, L_2);
Output_LinkList(L_3);
//清除空间
delete(L_1);
delete(L_2);
system("pause");
return 0;
}
RESULT InitList(LinkList &L) {
L = new LNode;
L->next = NULL;
return OK;
}
RESULT InsertData_Head(LinkList &L, int data) {
LinkList temp = new LNode;
temp->data = data;
temp->next = L;
L = temp;
return OK;
}
RESULT InsertData_Back(LinkList &L, int data) {
LinkList temp = new LNode;
temp->data = data;
temp->next = NULL;
LinkList p = L;
while (p->next != NULL) {
p = p->next;
}
p->next = temp;
return OK;
}
RESULT InsertData_Middle(LinkList& L, int NO, int data) {
LinkList temp = new LNode;
temp->data = data;
LinkList p = L;
for (int i = 0; i < NO - 2; i++) {
p = p->next;
}
temp->next = p->next;
p->next = temp;
return OK;
}
RESULT Output_LinkList(LinkList& L) {
LinkList temp = L->next;
while (temp != NULL) {
cout << temp->data << endl;
temp = temp->next;
}
return OK;
}
LinkList List_Combine(LinkList& L_1, LinkList& L_2) {
//链表指针
LinkList p_1 = L_1->next;
LinkList p_2 = L_2->next;
LinkList L_3 = new LNode;
LinkList p = L_3;
while (p_1 != NULL && p_2 != NULL) {
if (p_1->data == p_2->data) {
p->next = p_1;
p = p_1;
p_1 = p_1->next;
p_2 = p_2->next;
}
if (p_1->data < p_2->data) {
p->next = p_1;
p = p_1;
p_1 = p_1->next;
}
else {
p->next = p_2;
p = p_2;
p_2 = p_2->next;
}
}
if (p_1 == NULL && p_2 !=NULL) {
p->next = p_2;
}
if (p_2 == NULL && p_1 !=NULL) {
p->next = p_1;
}
return L_3;
}