刚开始写就直接写成了了一个 有序的链表 最后在把两个链表归并是有写了一个冒泡排序来排序 可能有点杂 写的不好见谅
#pragma once
#include<cstdio>
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<string>
#include<utility>
#include<vector>
#include<cstring>
#include<set>
#include <cmath>
#include<math.h>
using namespace std;
struct LIST
{
int data;//数据
LIST *next;//指向下一个位置
LIST(){this->next = NULL;}
};
//数据交换
inline void change(LIST *p, int data)
{
LIST *temp = (LIST *)malloc(sizeof(LIST));
temp->data = p->data;
temp->next = p->next;
p->data = data;
p->next = temp;
temp = NULL;
free(temp);
return;
}
class list
{
public :
LIST *head = NULL;//定义链表头
//排序链表用冒泡排序其他的有点难
inline int listsort()
{
LIST *p = head;
while (p != NULL)
{
LIST *temp = p->next;
while (temp!=NULL)
{
//交换两个位置
temp->data = temp->data > p->data ? temp->data : p->data;
p->data = temp->data < p->data ? temp->data : p->data;
temp = temp->next;
}
p = p->next;
}
return 0;
}
//向链表中添加数据
inline int insert(int data)
{
if (!head) { head = (LIST *)malloc(sizeof(LIST));head->data = data;head->next = NULL;return 0; }//如果头结点为空就向头结点添加
if (head->data>data)
{
change(head, data);//在头插入
return 0;
}
LIST *p = head->next;
LIST *last = head;
//找到要插入的位子
while (p != NULL)
{
if (p->data > data)
{
change(p, data);//在中间有小的位置就插入
return 0;
}
last = p;
p = p->next;
}
//在尾部插入
p = (LIST *)malloc(sizeof(LIST));
p->data = data;
p->next = NULL;
last->next = p;
last = NULL;
p = NULL;
free(last);
free(p);//释放空间
return 0;
}
//打印链表
inline int putout()
{
LIST *p = head;
if (!head) { cout << "该链表为空" << endl; return 0; }
while (p != NULL)
{
cout << p->data << endl;
p = p->next;
}
p = NULL;
free(p);
return 0;
}
//实现归并
inline int combine(list other)
{
LIST *tail = head;
if (head==NULL) { head = other.head; }
else
{
while (tail->next !=NULL ) { tail = tail->next; }
tail->next = other.head;
}
tail = NULL;
free(tail);
this->listsort();
return 0;
}
};
int main(int agrc, char argv[])
{
list head1;
list head2;
head2.insert(1);
head2.insert(6);
head2.insert(2);
head2.insert(3);
head2.insert(5);
head1.insert(2);
head1.insert(0);
head1.insert(-1);
head1.insert(1);
cout << "打印连表一:" << endl;
head1.putout();
cout << "打印连表二:" << endl;
head2.putout();
head1.combine(head2);
cout << "打印归并后的连表:" << endl;
head1.putout();
return 0;
}