题解 | #排序奇升偶降链表#
排序奇升偶降链表
http://www.nowcoder.com/practice/3a188e9c06ce4844b031713b82784a2a
面试遇到这个题,要求只能通过链表操作来完成..... 两个0%,很服气 分两步: 1、通过原来链表的性质,区分成两个子链表,偶数位是降序的,可以在分子链表的时候排序(其实就是前插就行了) 2、对两个有序的链表进行合并...
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
ListNode* sortLinkedList(ListNode* head) {
if (head == nullptr) {
return nullptr;
}
ListNode* pre = head;
ListNode* jHead = new ListNode(0);
ListNode* oHead = new ListNode(0);
//奇数位升序,偶数位降序, 返回升序
ListNode* cur1 = jHead;
int num = 1;
while (pre) {
if (num % 2 != 0) {
ListNode* node = new ListNode(pre->val);
cur1->next = node;
cur1 = cur1->next;
}
else if (num % 2 == 0) {
ListNode* cur2 = oHead;
ListNode* node = new ListNode(pre->val);
if(cur2->next == nullptr){
cur2->next = node;
}
else {
ListNode* next = cur2->next;
cur2->next = node;
node->next = next;
}
}
pre = pre->next;
num++;
}
//两个有序链表合并
ListNode* pre2 = oHead->next;
while (pre2) {
ListNode* pre1 = jHead->next;
ListNode* cur = jHead;
while (pre1) {
if (pre2->val < pre1->val) {
ListNode* node = new ListNode(pre2->val);
cur->next = node;
node->next = pre1;
break;
}
if (pre1->next != nullptr) {
if ((pre2->val > pre1->val) && (pre2->val < pre1->next->val)) {
ListNode* next = pre1->next;
ListNode* node = new ListNode(pre2->val);
pre1->next = node;
node->next = next;
break;
}
}
else {
ListNode* node = new ListNode(pre2->val);
pre1->next = node;
node->next = nullptr;
break;
}
pre1 = pre1->next;
cur = cur->next;
}
pre2 = pre2->next;
}
return jHead->next;
}
};