鍊錶的歸併排序,無需輔助外存

2021-08-20 09:31:09 字數 880 閱讀 2742

rt, 最近的面試題,面的時候敲的血崩,特此寫下部落格以作留念

如有錯誤,歡迎指正

class node

}public class test

system.out.print("歸併前:");

for (node i = head; i != null; i = i.next)

system.out.print(i.val + " ");

system.out.println();

head = mergesort(head, 10);

system.out.print("歸併後:");

for (node i = head; i != null; i = i.next)

system.out.print(i.val + " ");

system.out.println();

}//傳入煉表頭和鍊錶長度,返回新煉表頭,對以head開始的長度為len的鍊錶排序

private static node mergesort(node head, int len)

return head;

}//對以head開始的長度為len的鍊錶合併, [1, m]和[m+1, len]的兩條鍊錶

private static node merge(node head, int len, int m)

int l = 1;

int r = m + 1;

while (l <= m && r <= len) else else

p2 = p2pre.next;

++r;}}

return head;

}}雖然鍊錶的歸併無需輔存,但鍊錶的查詢增加了時間複雜度,而且寫的時候容易出錯,鍊錶的歸併也並不好用

鍊錶歸併排序

include include include include include using namespace std typedef int type typedef struct nodetag node node build type a,int n pnode pnext null retu...

鍊錶歸併排序

主要思路 1 如果為null或者只有乙個節點那麼直接返回 2 將鍊錶分成兩部分,分別進行排序,形成兩個有序鍊錶 3 將兩個有序鍊錶合併 void merge sort struct node list void split struct node head,struct node lista,str...

鍊錶 歸併排序

時間複雜度o nlogn 空間複雜度o 1 include include 定義鍊錶 typedef struct listnode linklist linklist head null 建立鍊錶 linklist createlist int arr,int len rear next null...