c++有序链表归并

        刚开始写就直接写成了了一个 有序的链表  最后在把两个链表归并是有写了一个冒泡排序来排序  可能有点杂 写的不好见谅大笑

#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;
}

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值