栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++实现接两个链表实例代码

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++实现接两个链表实例代码

 C++实现接两个链表实例代码

有以ha为头结点的链表,元素个数为m;以hb为头结点的链表,元素个数为n。现在需要你把这两个链表连接起来,并使时间复杂度最小,请分析并实现。

思路:

很简单的链表操作的题目,逆序头部插入,并将长度较长的一方接到较短的后面,时间复杂度为O(min(m,n)),注意free使用的地点!。

实例代码:

#include  
#include  
#include  
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<data<<" "; 
    plist=plist->next; 
  } 
  cout<next=NULL; 
  cout<<"逆序输入元素,空格分隔:"<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<<"合并后的链表为:"<next; 
    free(temp); 
  } 
} 
int main() 
{ 
  int m,n; 
  cout<<"请输入以ha为head节点链表的元素个数:"<>m; 
  linkList ha,hb,hc; 
  CreateList(ha,m); 
  cout<<"请输入以hb为head节点链表的元素个数:"<>n; 
  CreateList(hb,n); 
  Combine(ha,m,hb,n,hc); 
   
  Destory(hc); 
  return 0;   
} 

 感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/63825.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号