【100題】第四十一題 非降序鏈表的並集

來源:互聯網
上載者:User

一,題目

      兩個非降序鏈表的並集,1->2->3
和 2->3->5 並為 1->2->3->5。另外只能輸出結果,不能修改兩個鏈表的資料。

二,遞迴解法

 

#include <iostream>using namespace std;struct Node{    int data;    Node * next;}; Node * MergeRecursive(Node *head1 , Node *head2){  if ( head1 == NULL )    return head2 ;  if ( head2 == NULL)    return head1 ;  Node *head = new Node() ;  if ( head1->data < head2->data )  {    head = head1 ;    head->next = MergeRecursive(head1->next,head2);  }  else  {    head = head2 ;    head->next = MergeRecursive(head1,head2->next);  }  return head ;}Node *creatLink(int a[],int n){        Node *head=new Node();        head->data=a[0];        Node *tail=head;        head->next=NULL;        for(int i=1;i<n;++i)        {               Node *temp=new Node();               temp->data=a[i];               temp->next=NULL;                              tail->next=temp;               tail=tail->next;        }        return head;     }int main(){        int a[]={1,2,4,6,7};        int b[]={2,3,5,7,8};        Node *headA=creatLink(a,5);        Node *headB=creatLink(b,5);        Node *headResult= MergeRecursive(headA , headB);                while(headResult)        {               cout<<headResult->data<<" ";               headResult=headResult->next;        }} 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.