生活随笔
收集整理的這篇文章主要介紹了
【练习】c++删除链表倒数第K个结点和 插入排序算法将单链表递增排序
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
刪除單鏈表倒數第K個結點
運行結果:
代碼:
struct node
{int data
;node
* next
;};
bool delet(node
*& L
, int k
) {node
* p
, * q
, * t
;p
= L
;int i
= 0;while (i
< k
) {i
++;p
= p
->next
;}if (p
== NULL)return false;q
= L
;while (p
->next
!= NULL) {p
= p
->next
;q
= q
->next
;}t
= q
->next
;q
->next
= t
->next
;delete t
;return true;
}int main()
{srand(0);node
* m
= new node
;m
->data
= rand() % 5;node
* n
= new node
;n
->data
= rand() % 7;m
->next
= n
;node
* nn
= new node
;nn
->data
= rand() % 8;n
->next
= nn
;node
* jj
= new node
;jj
->data
= 100;jj
->next
= NULL;nn
->next
= jj
;node
* copy_m
= m
;cout
<< "第一個鏈表:";while (copy_m
) {cout
<< copy_m
->data
<<",";copy_m
= copy_m
->next
;}delet(m
, 2);copy_m
= m
;cout
<< "\n刪除結點后鏈表:";while (copy_m
) {cout
<< copy_m
->data
<<",";copy_m
= copy_m
->next
;}}
直接插入將單鏈表遞增排序
結果:
void sort(node
*& L
) {node
* p
= L
->next
->next
;node
* q
;L
->next
->next
= NULL;node
* pre
= L
;while (p
!= NULL) {pre
= L
;q
= p
->next
;while (pre
->next
!= NULL && pre
->next
->data
< p
->data
)pre
= pre
->next
;p
->next
= pre
->next
;pre
->next
= p
;p
= q
;}
}
int main()
{srand(0);node
* begin
=new node
;begin
->next
= NULL;node
* m
= new node
;m
->data
= rand() % 15;m
->next
= begin
->next
;begin
->next
= m
;node
* n
= new node
;n
->data
= rand() % 7;n
->next
= begin
->next
;begin
->next
= n
;node
* nn
= new node
;nn
->data
= rand() % 20;nn
->next
= begin
->next
;begin
->next
= nn
;node
* jj
= new node
;jj
->data
= 10;jj
->next
= begin
->next
;begin
->next
= jj
;node
* copy_m
= begin
;cout
<< "第一個鏈表:";while (copy_m
->next
) {cout
<< copy_m
->next
->data
<<",";copy_m
= copy_m
->next
;}sort(begin
);copy_m
= begin
;cout
<< "\n排序結點后鏈表:";while (copy_m
->next
) {cout
<< copy_m
->next
->data
<<",";copy_m
= copy_m
->next
;}}
注意,這里在自己初始化鏈表的時候發現:
只有寫成
while (copy_m
->next
) {cout
<< copy_m
->next
->data
<<",";copy_m
= copy_m
->next
;}
時才能正確輸出排序后的結果,
如果寫成
while (copy_m
) {copy_m
= copy_m
->next
;cout
<< copy_m
->data
<<",";}
是無法得到排序后結果的。
總結
以上是生活随笔為你收集整理的【练习】c++删除链表倒数第K个结点和 插入排序算法将单链表递增排序的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。