两个单链表的有序合并

#include
#include<malloc.h>
#include
#include
using namespace std;

struct Linklist{
int val;
struct Linklist *next;
};

struct Linklist *Creatlist(){
struct Linklist *head,current,p;
head = (struct Linklist
)malloc(sizeof(struct Linklist));
current = head;
int data;
cout<<“input data:”<<endl;
cin>>data;
while(data != -1){
p = (struct Linklist
)malloc(sizeof(struct Linklist));
p -> val = data;
current->next = p;
current = p;
cin>>data;
}
current ->next = NULL;
return head;
}

int Length(struct Linklist *head)
{
if(head == NULL){
return 0;
}
struct Linklist *p;
p = head;
p = p->next;
int length = 0;
while(p != NULL)
{
length++;
p = p->next;
}
return length;
}

void *Merge(struct Linklist *L1,struct Linklist *L2){
struct Linklist *current;
current = L1;
while(current -> next)
{
current = current->next;
}
current -> next = L2 ->next;
free(L2);
}

void Show(struct Linklist *p){
struct Linklist *current;
current = p;
current = current->next;
while(current != NULL){
cout<val<<" ";
current = current->next;
}
cout<<endl;
}

void SortList(struct Linklist *head)
{
int length = Length(head);
//cout<<length<<endl;
if (length == 0){
return;
}
struct Linklist *p;
p = head;
p = p->next;
int i, j, sum;
for (i = 0; i < length - 1; i++)
{
p = head;
p = p->next;
for (j = 0; j < length -i -1; j++)
{
if (p->val > p->next->val)
{
sum = p->val;
p->val = p->next->val;
p->next->val = sum;
}
p = p->next;
}
}
}

int main(){
struct Linklist *L1,*L2,*L3;
L1 = Creatlist();
L2 = Creatlist();
Merge(L1,L2);
cout<<“合并前:”<<endl;
Show(L1);
SortList(L1);
cout<<“合并之后:”<<endl;
Show(L1);
}

我的方法是先把两个链表合并,然后再对合并后的链表进行排序,个人觉得这样比较简单。然后推荐一个B站up主的视频,Lellansin的链表,我感觉挺好的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值