c/c++:单链表的拆分

数据结构实验之链表五:单链表的拆分

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

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

    struct node *head , *tail,*p;

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

    int num;
    int sum1,sum2;

    cin>>num;
    while(num--)
    {
        p = new node ;
        cin>>p->data;
        tail->next = p;
        tail = tail->next;
    }
    p->next = NULL;


    struct node *head1 , *head2 ,*tail1,*tail2;

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

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

    p = head->next;
    sum1 = 0;
    sum2 = 0;
    while(p!=NULL){

        if(p->data%2 ==1){
            tail1->next = p;
            tail1 = tail1->next;
            sum1 +=1;
        } else {
            tail2->next = p;
            tail2 = tail2->next;
            sum2 +=1;
        }
        p = p->next;
    }
    tail1->next = NULL;
    tail2->next = NULL;
    cout << sum2 << ' '<<sum1<<endl;

    p = head2->next;
    while(p!=NULL){
        cout<<p->data;
        if(p->next!=NULL){
            cout<< ' ';
        }
        p = p->next;

    }
    cout<<endl;

    p = head1->next;
    while(p!=NULL){
        cout<<p->data;
        if(p->next!=NULL){
            cout<< ' ';
        }
        p = p->next;

    }
    cout<<endl;

    return 0;

}

评论列表