日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

【练习】c++删除链表倒数第K个结点和 插入排序算法将单链表递增排序

發布時間:2024/9/30 c/c++ 53 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【练习】c++删除链表倒数第K个结点和 插入排序算法将单链表递增排序 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

刪除單鏈表倒數第K個結點

運行結果:


代碼:

struct node {int data;node* next;}; //刪除鏈表的倒數第k個結點 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;//cout << m->data;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;//注意每次最外面的while中都要初始化preq = p->next;//q保存當前p結點的后繼結點while (pre->next != NULL && pre->next->data < p->data)pre = pre->next;p->next = pre->next;//當pre->next->data>p->data 在pre后面插入p結點 因為p的數據更小 按遞增排序pre->next = p;p = q;//p指向原來的后繼結點} } int main() {srand(0);node* begin=new node;begin->next = NULL;node* m = new node;m->data = rand() % 15;//cout << m->data;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个结点和 插入排序算法将单链表递增排序的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。