您的位置:首页 > 其它

单链表进行奇偶整数位置调整

2016-03-03 17:17 253 查看


92005:单链表进行奇偶整数位置调整

Time/Memory Limit:1000 MS/32768 K 
Submitted: 107 Accepted: 61




 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





 Hints

注意从测试数据的长度和奇偶性两方面考虑输出的特殊情况。





 Author

txq




 Recommend

zh

#include<iostream>

using namespace std;

struct Node{int data;Node*next;};

int main()

{
int n1,n,n2,t,c,a[100],i;
Node*first,*s,*p,*q,*r;
cin>>t;
while(t--)
{
cin>>n;
first=new Node;first->next=NULL;r=first;
for(i=0;i<n;i++)
{
cin>>a[i];
s=new Node;s->data=a[i];s->next=r->next;r->next=s;r=s;}//建立单链表
n1=0;p=first->next;
while(p)
{
if(p->data%2!=0)
{
n1++;//计算奇数段长度
}
p=p->next;
}
c=0;p=first->next;
while(p)
{
if(p->data%2!=0)
{
c++;//设立标记数字控制输出
if(c<n1){
cout<<p->data<<" ";
}
else if(c==n1){
cout<<p->data;
break;
}
}
p=p->next;
}

cout<<endl;

n2=n-n1;//计算偶数段长度

p=first->next;c=0;

while(p)

{
if(p->data%2==0)
{
c++;
if(c<n2)
{
cout<<p->data<<" ";//输出偶数段
}
else if(c==n2)
{
cout<<p->data;break;
}
}
p=p->next;

}

cout<<endl;

while(first)

{q=first;first=first->next;delete q;}//清理垃圾
}
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: