迭代单链表排序

题目:

  给定一个节点数为n的无序单链表,对其按升序排序。

 
  数据范围:0<n≤1000000<n100000
  要求:时间复杂度 O(nlogn)O(nlogn)
 
迭代实现:

/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/

class Solution {
public:
ListNode* merge(ListNode* h1, ListNode* h2){
ListNode* vhead = new ListNode(-1);
ListNode* tail = vhead;
while(NULL!=h1 && NULL!=h2){
if(h1->val <= h2->val){
tail->next = h1;
h1 = h1->next;
} else {
tail->next = h2;
h2 = h2->next;
}

tail = tail->next;
}

if(NULL != h1){
tail->next = h1;
}

if(NULL != h2) {
tail->next = h2;
}

return vhead->next;
}

int length(ListNode* head){
if(NULL == head){
return 0;
}

int cnt = 0;
while(NULL != head){
++cnt;
head = head->next;
}

return cnt;
}

/**
*
* @param head ListNode类 the head node
* @return ListNode类
*/
ListNode* sortInList(ListNode* head) {
// write code here
int len = length(head);
ListNode* res = head;

for(int step=1; step<len; ){
ListNode* vhead = new ListNode(-1);
ListNode* ntail = vhead;
ListNode* ps1 = res;
ListNode* pe1 = res;
ListNode* ps2 = res;
ListNode* pe2 = res;
ListNode* ns = res;

while(NULL != ps1) {
bool stop = false;
// 找pe1和ps2
int i=0;
for(i=0; i<step && !stop; ++i){
if(NULL != ps2) {
pe1 = ps2;
ps2 = ps2->next;
} else {
stop = true;
ps2 = NULL;
pe2 = NULL;
ns = NULL;
}
}
if(NULL != pe1) {
pe1->next = NULL;
}
//找pe2和ns
pe2 = ps2;
for(i=1; i<step && !stop && (NULL!=pe2) && (NULL!=pe2->next); ++i){
pe2 = pe2->next;
}

if(NULL!=pe2){
ns = pe2->next;
pe2->next=NULL;
} else{
ns=NULL;
}

ntail->next = merge(ps1, ps2);
while(NULL != ntail->next) {
ntail = ntail->next;
}

ps1 = ns;
ps2 = ps1;
}

res = vhead->next;
step = step*2;
}

return res;
}
};

posted @ 2022-08-06 00:40  修心而结网  阅读(42)  评论(0编辑  收藏  举报