运用递归将两个链表进行连接

来源:互联网 发布:软件开发包括哪些课程 编辑:程序博客网 时间:2024/05/20 01:11

http://blog.csdn.net/zjut_ym/article/details/45008259

  • 建立2个数据项按从大到小排列的链表,实现2个链表的合并,并输出合并后链表的数据项。

函数代码如下

#include<iostream>using namespace std;struct node{    int data;    node *next;};node *head=NULL;node *tail=NULL;node *temp;node *createlist(int n){   int num;   cin>>num;   head=new node;    if(head==NULL)   {      cout<<"No memory available!";      return NULL;   }   else   {      head->data=num;      head->next=NULL;      tail=head;   }   for(int i=0;i<n-1;i++)   {      cin>>num;      temp=new node;        if(temp==NULL){         cout<<"No memory available!";         return head;    }    else    {      temp->data=num;      temp->next=NULL;      tail->next=temp;      tail=temp;    }   }   return head;}void display(node *head){    cout<<"List is :"<<endl;    while(head)    {        cout<<head->data<<" ";        head=head->next;    }    cout<<endl;}node *link(node *a,node *b){    node *c=NULL;    if(a==NULL)        return b;    else if(b==NULL)        return a;    if(a->data<=b->data)    {        c=a;        c->next=link(a->next,b);    }    else    {        c=b;        c->next=link(a,b->next);    }    return c;}int main(){    int n,m;    node *a,*b,*c;    cout<<"请按从小到大的顺序依次输入两组数据:"<<endl;    cout<<"第一组数据长度个数为:"<<endl;    cin>>n;    cout<<"请输入第一组数据"<<endl;    a=createlist(n);    cout<<"第二组数据长度个数为:"<<endl;    cin>>m;    cout<<"请输入第二组数据"<<endl;    b=createlist(m);    c=link(a,b);    cout<<"将两组数据从小到大连接后:"<<endl;    display(c);    return 0;}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89

运行结果


原创粉丝点击