分而治之:通過遞迴把乙個無序鍊錶對半分成許多小煉表,然後對這些小煉表兩兩之間進行歸併(合併有序鍊錶),從而最終使整個鍊錶有序。
#include
using
namespace std;
template
<
class
t>
struct chainnode//定義鍊錶節點
chainnode
(const t& theelement, chainnode
* thenext)};
template
<
class
t>
class
chain
void
push
(const t& theelement)
//只提供頭插法
void
mergesort()
void
print()
cout << endl;
}private
: chainnode
* first;
int size;
chainnode
*merge
(chainnode
* head1, chainnode
* head2)
//合併兩個有序鍊錶實現歸併
else
currentnode = currentnode-
>next;
}//之後把未到達結尾的鍊錶加入到合併鍊錶中
if(head1 !=
nullptr
) currentnode-
>next = head1;
if(head2 !=
nullptr
) currentnode-
>next = head2;
return top.next;
} chainnode
*mergesort
(chainnode
* thefirst)
chainnode
* head2 = slownode-
>next;
//head2是後半段鍊錶的頭節點
slownode-
>next =
nullptr
;//刪除後半段
chainnode
* head1 = thefirst;
//head1是前半段鍊錶的頭節點
head1 =
mergesort
(head1)
; head2 =
mergesort
(head2)
;return
merge
(head1, head2)
;//返回兩段有序鍊錶歸併之後的鍊錶}}
;int
main()
c.mergesort()
; c.
print()
;}
鍊錶歸併排序
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...