#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;
}
运行结果: