最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C++實(shí)現(xiàn)接兩個(gè)鏈表實(shí)例代碼

 更新時(shí)間:2017年03月01日 08:37:32   投稿:lqh  
這篇文章主要介紹了C++實(shí)現(xiàn)接兩個(gè)鏈表實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下

 C++實(shí)現(xiàn)接兩個(gè)鏈表實(shí)例代碼

有以ha為頭結(jié)點(diǎn)的鏈表,元素個(gè)數(shù)為m;以hb為頭結(jié)點(diǎn)的鏈表,元素個(gè)數(shù)為n?,F(xiàn)在需要你把這兩個(gè)鏈表連接起來,并使時(shí)間復(fù)雜度最小,請(qǐng)分析并實(shí)現(xiàn)。

思路:

很簡單的鏈表操作的題目,逆序頭部插入,并將長度較長的一方接到較短的后面,時(shí)間復(fù)雜度為O(min(m,n)),注意free使用的地點(diǎn)!。

實(shí)例代碼:

#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<<"請(qǐng)輸入以ha為head節(jié)點(diǎn)鏈表的元素個(gè)數(shù):"<<endl; 
  cin>>m; 
  LinkList ha,hb,hc; 
  CreateList(ha,m); 
  cout<<"請(qǐng)輸入以hb為head節(jié)點(diǎn)鏈表的元素個(gè)數(shù):"<<endl; 
  cin>>n; 
  CreateList(hb,n); 
  Combine(ha,m,hb,n,hc); 
   
  Destory(hc); 
  return 0;   
} 

 感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

相關(guān)文章

最新評(píng)論

宁南县| 星子县| 义马市| 调兵山市| 介休市| 扬州市| 吉水县| 咸丰县| 仁布县| 临沧市| 饶阳县| 仁布县| 申扎县| 忻州市| 龙岩市| 万州区| 财经| 安多县| 体育| 梁平县| 崇左市| 宁南县| 工布江达县| 玉山县| 黄骅市| 高台县| 高邑县| 松桃| 泰安市| 惠来县| 田林县| 永昌县| 张北县| 定兴县| 澄迈县| 荔波县| 庄浪县| 田阳县| 连山| 齐河县| 多伦县|