1. 程式人生 > >合併兩個有序連結串列,合併之後任然是有序的並輸出。

合併兩個有序連結串列,合併之後任然是有序的並輸出。

合併連結串列相信大家都特別熟悉,但是如果要加上一定的輸出格式,難度就會有所增加,不說了,見程式碼。

#include<iostream>
using namespace std;
struct Node{
    Node *next;
    int data;
};

void nodeprint(Node *head){
    Node *node=head;
    while(node){
        cout<<node->data<<"->";
        node=node->next;
    }
    cout<<endl;
}
Node* buildList(int arr[],int n){
    if(n==0) return NULL;
    Node *head=new Node();
    head->data=arr[0];
    head->next=NULL;
    Node *p=head;
    Node *q;
    for(int i=1;i<n;i++){
        q=new Node();
        q->data=arr[i];
        q->next=NULL;
        p->next=q;
        p=p->next;
    }
    return head;

}

Node * Merge(Node *head1 , Node *head2)
{
    if ( head1 == NULL)
        return head2 ;
    if ( head2 == NULL)
        return head1 ;
    Node *head = NULL ;
    Node *p1 = NULL;
    Node *p2 = NULL;
    if ( head1->data < head2->data )
    {
        head = head1 ;
        p1 = head1->next;
        p2 = head2 ;
    }
    else
    {
        head = head2 ;
        p2 = head2->next ;
        p1 = head1 ;
    }
    Node *pcurrent = head ;
    while ( p1 != NULL && p2 != NULL)
    {
        if ( p1->data <= p2->data )
        {
            pcurrent->next = p1 ;
            pcurrent = p1 ;
            p1 = p1->next ;
        }
        else
        {
            pcurrent->next = p2 ;
            pcurrent = p2 ;
            p2 = p2->next ;
        }
    }
    if ( p1 != NULL )
        pcurrent->next = p1 ;
    if ( p2 != NULL )
        pcurrent->next = p2 ;
    return head ;
}
 int main(){
     int arr1[100];
     int arr2[100];
     int m,n;

     cin>>m>>n;;
    for(int i=0;i<m;i++)
        cin>>arr1[i];
    for(int j=0;j<n;j++)
        cin>>arr2[j];
    Node *head1=buildList(arr1,m);
    Node *head2=buildList(arr2,n);
    Node *tem=Merge(head1,head2);
    nodeprint(tem);
    return 0;
}