c/c++:有序链表的归并

数据结构实验之链表四:有序链表的归并

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


int main ()
{
    std::ios::sync_with_stdio(false);

    int length1,length2;
    struct node *head1,*head2,*tail1,*tail2,*p1,*p2,*tmp;

    head1 = new node;
    tail1 = head1;
    head1->next = NULL;

    head2 = new node ;
    tail2 = head2;
    head2->next = NULL;


    cin >>length1>>length2;

    while(length1 -- )
    {
        p1 = new node ;
        cin>>p1->data;
        tail1->next = p1;
        tail1 = p1;
    }
    p1->next = NULL;

    while(length2 -- )
    {
        p2 = new node ;
        cin>>p2->data;
        tail2->next = p2;
        tail2 = p2;
    }
    p2->next = NULL;

    p1 = head1;
    p2 = head2;


    struct node *head,*tail;

    head = new node;
    head->next = NULL;
    tail = head;

    p1 = head1->next;
    p2 = head2->next;


    while(p1&&p2){
        if(p1->data < p2->data){
            tail->next = p1;
            p1 = p1->next;
        } else {
            tail->next = p2;
            p2 = p2->next;
        }
        tail = tail->next;
    }


    if(p1){
        tail->next = p1;
    } else {
        tail->next = p2;
    }

    delete(head2);
    delete(head1);

    p1 = head->next;
    while(p1->next!=NULL){
        cout<<p1->data<<' ';
        p1 = p1->next;
    }

    cout << p1->data<<endl;

    return 0;
}

评论列表