欧美大屁股bbbbxxxx,狼人大香伊蕉国产www亚洲,男ji大巴进入女人的视频小说,男人把ji大巴放进女人免费视频,免费情侣作爱视频

歡迎來到入門教程網(wǎng)!

C語言

當(dāng)前位置:主頁 > 軟件編程 > C語言 >

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

來源:本站原創(chuàng)|時(shí)間:2020-01-10|欄目:C語言|點(diǎn)擊: 次

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

有以ha為頭結(jié)點(diǎn)的鏈表,元素個(gè)數(shù)為m;以hb為頭結(jié)點(diǎn)的鏈表,元素個(gè)數(shù)為n。現(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ì)本站的支持!

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫服務(wù)器

如果侵犯了您的權(quán)利,請(qǐng)與我們聯(lián)系,我們將在24小時(shí)內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有