单链表奇数升序偶数降序,将链表整体变成升序(C++实现)

#include<iostream>
using namespace std;

//定义链表结构
struct linkList
{
	int val;
	struct linkList* next;
	linkList(int x) :val(x), next(NULL){

	}

};
//链表合并排序
linkList* mergelist(linkList* ohead, linkList* jhead){
	/*//定义头结点简单
	linkList* new_head = new linkList(-1);
	linkList* cur = new_head;
	//两个链表都存在时继续往下走
	while (ohead && jhead){
		//
		if (ohead->val < jhead->val){
			cur->next = ohead;
			ohead = ohead -> next;
		}
		else{
			cur->next = jhead;
			jhead = jhead->next;
		}
		cur = cur->next;
	}*/
	//不定义任何新的节点时
	linkList* head = nullptr;
	linkList* cur = nullptr;
	while (ohead && jhead){
		//拿出插入的结点
		linkList* p = ohead->val < jhead->val ? ohead : jhead;
		if (p == ohead)
			ohead = ohead->next;
		if (p == jhead)
			jhead = jhead->next;
		//判断此时是否是空结点
		if (head == nullptr){
			head = p;
			cur = p;
		}
		else{
			cur->next = p;
			cur = cur->next;
		}
	}
	//判断两个链表是否为空,将不为空的链表接在新链表的后面
	if (ohead == nullptr)
		cur->next = jhead;
	if (jhead == nullptr)
		cur->next = ohead;
	return head;

}
//奇结点链表反转
linkList* reveslist(linkList* jhead){
	if (jhead->next == nullptr)
		return jhead;
	linkList* pre = jhead;
	linkList* mid = jhead->next;
	linkList* last = mid->next;
	while (last){
		//反转
		mid->next = pre;
		//整体后移
		pre = mid;
		mid = last;
		last = last->next;
	}
	//此时最后的mid结点还没有反转
	mid->next = pre;
	//第一个结点还有反转
	jhead->next = nullptr;
	return mid;
}
//链表拆分 偶结点升序,奇结点降序
linkList* splitlist(linkList* head){
	//判断临界点
	if (head == nullptr || head->next == nullptr)
		return head;
	//定义拆分后的链表
	linkList* ohead = nullptr;
	linkList* ocur = nullptr;
	linkList* jhead = nullptr;
	linkList* jcur = nullptr;

	int num = 0;
	while (head){
		if ((num & 1) == 0){
			if (ohead == nullptr){
				ohead = head;
				ocur = head;
			}
			else{
				ocur->next = head;
				ocur = ocur->next;
			}
		}
		else{
			if (jhead == nullptr){
				jhead = head;
				jcur = head;
			}
			else{
				jcur->next = head;
				jcur = jcur->next;
			}
		}
		head = head->next;
		num++;
	}
	//将奇偶数链表与之前链表断开
	ocur->next = nullptr;
	jcur->next = nullptr;
	linkList* rejhead = reveslist(jhead);
	return mergelist(ohead, rejhead);
}

int main(int argc, char * argv){
	linkList p0(1), p1(100), p2(11), p3(60),p4(50),p5(30);
	p0.next = &p1;
	p1.next = &p2;
	p2.next = &p3;
	p3.next = &p4;
	p4.next = &p5;
	linkList * result = splitlist(&p0);
	while (result){
		cout << result->val << " ";
		result = result->next;
	}
	cout << endl;
	system("pause");
	return 0;

}

运行结果:
在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值