6(1)
思路
1、这个思路就是链表版本归并排序,中的一步,拿来两个单独的链表,怎么用串糖葫芦的方法把他们连成一个整体,详细解释见:第八章–排序
2、注意一点:“头插法” 与 “尾插法”
<1>头插法:链表向左侧增长,最后head指向最大的节点,所以产生递减序列
<2>尾插法:链表向右侧增长,head始终不动,由tail指引不断插入,随后产生递增序列
代码
这种合并算法,一定记住,产生合并式的时候有哨兵节点,随后要把哨兵去掉
#include <iostream>
#include <string>
#include <stack>
#include <queue>
#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;
typedef struct node {
int val;
node* next;
}node;
node* merge(node* left, node* right) {//头插法:递减 尾插法:递增
node* head = (node*)malloc(sizeof(node));
while (left != nullptr&&right != nullptr) {
if (left->val >= right->val) {
node* tmp = left;
left = left->next;
tmp->next = head->next;
head->next = tmp;
}
else {
node* tmp = right;
right = right->next;
tmp->next = head->next;
head->next = tmp;
}
}
while (left != nullptr) {
node* tmp = left;
left = left->next;
tmp->next = head->next;
head->next = tmp;
}
while (right != nullptr) {
node* tmp = right;
right = right->next;
tmp->next = head->next;
head->next = tmp;
}
return head->next;//插入时利用哨兵节点方便插入,最后舍弃哨兵
}