面經筆記 鍊錶歸併排序

2021-08-04 06:32:34 字數 1040 閱讀 8232

鍊錶適合歸併排序

時間複雜度:o(nlogn)

空間複雜度:o(1)

穩定性:穩定

#include 

using namespace std;

class node

; node(int i);

node* next;

int val;

};node* merge(node* pleft, node* pright)

if (pright == null)

node dummy;

node* ptmp = &dummy;

while (pleft != null&&pright != null)

else

}if (pleft!=null)

if (pright!=null)

return dummy.next;

}node * mergesort(node * phead)

node * pfast(phead);

node * pslow(phead);

while (pfast->next != null&&pfast->next->next != null)

//while (pfast != null&&pfast->next != null)錯誤,無法分割兩個點

node * pleftpart = phead;

node * prightpart = pslow->next;

pslow->next = null;

pleftpart = mergesort(pleftpart);

prightpart = mergesort(prightpart);

return merge(pleftpart, prightpart);

}int main()

return

0;}

查詢中間節點使用快慢指標

while (pfast != null&&pfast->next != null) //無法分割兩個點的情況

鍊錶歸併排序

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...