C++實現(xiàn)接兩個鏈表實例代碼
更新時間:2017年03月01日 08:37:32 投稿:lqh
這篇文章主要介紹了C++實現(xiàn)接兩個鏈表實例代碼的相關(guān)資料,需要的朋友可以參考下
C++實現(xiàn)接兩個鏈表實例代碼
有以ha為頭結(jié)點的鏈表,元素個數(shù)為m;以hb為頭結(jié)點的鏈表,元素個數(shù)為n?,F(xiàn)在需要你把這兩個鏈表連接起來,并使時間復(fù)雜度最小,請分析并實現(xiàn)。
思路:
很簡單的鏈表操作的題目,逆序頭部插入,并將長度較長的一方接到較短的后面,時間復(fù)雜度為O(min(m,n)),注意free使用的地點!。
實例代碼:
#include <iostream> #include <string> #include <algorithm> using namespace std; typedef int ElemType; typedef struct Node { ElemType data; struct Node *next; }Lnode,*LinkList; //打印 void print(LinkList &head) { LinkList plist=head->next; while(plist!=NULL) { cout<<plist->data<<" "; plist=plist->next; } cout<<endl; } //逆序輸入鏈表 void CreateList(LinkList &L,int m) { LinkList p; L=(LinkList)malloc(sizeof(Node)); L->next=NULL; cout<<"逆序輸入元素,空格分隔:"<<endl; for(int i=m;i>0;--i) { p=(LinkList)malloc(sizeof(Node)); cin>>p->data; p->next=L->next; L->next=p; } print(L); } //連接鏈表 void Combine(LinkList &ha,int m,LinkList &hb,int n,LinkList &hc) { LinkList selectMin; hc=(LinkList)malloc(sizeof(Node)); int flag=0; if(m>n) { selectMin=hb; flag=1; //ha在后面 } else selectMin=ha; while(selectMin->next!=NULL) selectMin=selectMin->next; if(flag) { selectMin->next=ha->next; hc=hb; free(ha);//notice } else { selectMin->next=hb->next; hc=ha; free(hb); } cout<<"合并后的鏈表為:"<<endl; print(hc); } void Destory(LinkList &hc) //僅釋放hc即可 { LinkList temp; while(hc!=NULL) { temp=hc; hc=hc->next; free(temp); } } int main() { int m,n; cout<<"請輸入以ha為head節(jié)點鏈表的元素個數(shù):"<<endl; cin>>m; LinkList ha,hb,hc; CreateList(ha,m); cout<<"請輸入以hb為head節(jié)點鏈表的元素個數(shù):"<<endl; cin>>n; CreateList(hb,n); Combine(ha,m,hb,n,hc); Destory(hc); return 0; }
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
Cocos2d-x中使用CCScrollView來實現(xiàn)關(guān)卡選擇實例
這篇文章主要介紹了Cocos2d-x中使用CCScrollView來實現(xiàn)關(guān)卡的選擇實例,本文在代碼中用大量注釋講解了CCScrollView的使用,需要的朋友可以參考下2014-09-09C/C++ int數(shù)與多枚舉值互轉(zhuǎn)的實現(xiàn)
在C/C++在C/C++的開發(fā)中經(jīng)常會遇到各種數(shù)據(jù)類型互轉(zhuǎn)的情況,本文主要介紹了C/C++ int數(shù)與多枚舉值互轉(zhuǎn)的實現(xiàn),具有一定的參考價值,感興趣的可以了解一下2021-08-08詳解_beginthreadex()創(chuàng)建線程
這篇文章主要介紹了詳解_beginthreadex()創(chuàng)建線程,使用_beginthreadex(),需要的頭文件支持#include <process.h> 下面我們就來看看具體的實現(xiàn)吧2022-01-01