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

歡迎訪問 生活随笔!

生活随笔

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

c/c++

【练习】c++单向链表求交集

發布時間:2024/9/30 c/c++ 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【练习】c++单向链表求交集 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

思路:先遞增排序再二路歸并


代碼:

//直接插入排序 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->d%ata 在pre后面插入p結點 因為p的數據更小 按遞增排序pre->next = p;p = q;//p指向原來的后繼結點} }void jiao(node* a, node* b, node*& c) {node* pa = a->next, * pb = b->next;node* s, * r;c = new node;// c->next = NULL;r = c;while (pa != NULL && pb != NULL) {if (pa->data == pb->data) {s = new node;s->data = pa->data;s->next = c->next;c->next = s;pa = pa->next;pb = pb->next;}else if (pb->data < pa->data) {pb = pb->next;}else {pa = pa->next;}}}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;sort(begin);node* copy_m = begin;cout << "第一個鏈表:";while (copy_m->next) {cout << copy_m->next->data << ",";copy_m = copy_m->next;}node* begin2 = new node;begin2->next = NULL;node* m2 = new node;m2->data = rand() % 15;//cout << m->data;m2->next = begin2->next;begin2->next = m2;node* n2 = new node;n2->data = 5;n2->next = begin2->next;begin2->next = n2;node* nn2 = new node;nn2->data = 8;nn2->next = begin2->next;begin2->next = nn2;node* jj2 = new node;jj2->data = 10;jj2->next = begin2->next;begin2->next = jj2;node* copy_m2 = begin2;sort(begin2);cout << "第二個鏈表:";while (copy_m2->next) {cout << copy_m2->next->data << ",";copy_m2 = copy_m2->next;}cout << endl;cout << "交集:";node* c = new node;c->next = NULL;jiao(begin, begin2, c);while (c != NULL) {cout << c->next->data<<"->";c = c->next;}}

總結

以上是生活随笔為你收集整理的【练习】c++单向链表求交集的全部內容,希望文章能夠幫你解決所遇到的問題。

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