链表拆分
2016-07-26 19:08
274 查看
题目描述
输入N个整数顺序建立一个单链表,将该单链表拆分成两个子链表,第一个子链表存放了所有的偶数,第二个子链表存放了所有的奇数。两个子链表中数据的相对次序与原链表一致。输入
第一行输入整数N;;第二行依次输入N个整数。
输出
第一行分别输出偶数链表与奇数链表的元素个数;第二行依次输出偶数子链表的所有数据;
第三行依次输出奇数子链表的所有数据。
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node*next;
};
int main()
{
int n,i,x=0,y=0;
struct node*head1,*head2,*p,*q;
scanf("%d",&n);
head1=(struct node*)malloc(sizeof(struct node));
head1->next=NULL;
for(i=0; i<=n-1; i++)
{
p=(struct node*)malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next=NULL;
p->next=head1->next;
head1->next=p;
}
p=head1->next;
q=p->next;
head1->next=NULL;
head2=(struct node*)malloc(sizeof(struct node));
head2->next=NULL;
while(p!=NULL)
{
if(p->data%2==0)
{
x++;
p->next=head1->next;
head1->next=p;
}
else
{
y++;
p->next=head2->next;
head2->next=p;
}
p=q;
if(q!=NULL)
q=q->next;
}
printf("%d %d\n",x,y);
p=head1->next;
while(p!=NULL)
{
if(p->next!=NULL)
printf("%d ",p->data);
else printf("%d\n",p->data);
p=p->next;
}
p=head2->next;
while(p!=NULL)
{
if(p->next!=NULL)
printf("%d ",p->data);
else printf("%d\n",p->data);
p=p->next;
}
return 0;
}
分开head1和head2 ,p和q在一条链上谁符合要求就加在哪条链后
相关文章推荐
- 整理:CString类的完美总结&&CString 成员函数用法大全&&string 与 CString 转化&&<string><string.h> 和<cstring>的区别
- WebService基础学习(一)—基础知识
- 把docker当做绿色打包工具
- 二值化图像的颜色翻转
- 离散什么的
- C++ builder消息的运用
- 单链表中重复元素的删除
- 关于数组,函数的一个简单例子(打渔晒网)
- 达内学习笔记——const 指针
- 我对PID的理解
- react研究(一)
- CSR1010蓝牙开发I/O操作
- POJ 2752 既是前缀又是后缀
- 顺序表应用1:多余元素删除之移位算法
- 【字符串1】-替换空格
- 排序算法(OC实现)
- linux第二天总结
- 一个Mina实例
- Google推荐的图片加载库Glide
- Elasticsearch Java Api(六)--DeleteByQuery