92005:单链表进行奇偶整数位置调整
Problem Description
要求以非空单链表完成以下操作:
输入n(0<n<=50)个整数,每两个数之间以空格分隔,现要求:
1. 先输出其中的奇数,并按输入的相对顺序排列;
2. 然后输出其中的偶数,并按输入的相对顺序排列。
该题必须用单链表完成,否则0分!!!
Input
第一行为一个整数m,表示下面有m组测试数据,每组包括两行:
每组测试数据的第一行为一个整数n(0<n<=50),表示表长;
每组测试数据的第二行有n个整数,表示表的各元素。
Output
每组测试数据的输出均占两行:
第一行输出所有奇数,每两个数之间以一个空格分隔;
第二行输出所有偶数,每两个数之间以一个空格分隔。
Sample Input
2 10 4 7 3 13 11 12 0 47 34 98 8 1 65 3 5 2 1 4 5
Sample Output
7 3 13 11 47 4 12 0 34 98 1 65 3 5 1 5 2 4
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
struct node {
int data;
node* next;
};
class List {
public:
node* head;
List() {
head=new node;
head->next=NULL;
}
void creat(int n) {
node* r=head;
int num;
for(int i=0; i<n; i++) {
cin>>num;
node* s=new node;
s->data=num;
r->next=s;
r=s;
}
r->next=NULL;
}
void List_odd(node* odd) {
node* cur=head;
node* p=odd;
while(cur->next) {
if(cur->next->data%2==0) {
p->next=cur->next;
p=cur->next;
node* temp=cur->next;
cur->next=temp->next;
} else {
cur=cur->next;
}
}
p->next=NULL;
}
~List() {
if(head==NULL||head->next==NULL)return;
node* p=head->next;
while(p) {
node* temp=p;
p=p->next;
delete temp;
}
}
void print() {
if(head->next==NULL||head==NULL) {
cout<<endl;
} else {
node* p=head->next;
while(p->next) {
cout<<p->data<<" ";
p=p->next;
}
cout<<p->data<<endl;
}
}
};
int main() {
int T;
while(cin>>T) {
while(T--) {
int n;
cin>>n;
List list;
list.creat(n);
List list_B;
list.List_odd(list_B.head);
list.print();
// print(ret);
list_B.print();
}
}
return 0;
}