数据结构实验之链表五:单链表的拆分
来源:互联网 发布:淘宝店铺设置在哪里 编辑:程序博客网 时间:2024/05/16 17:40
这道题的算法思想就是将一个单链表拆分成两个单链表,也就是说再建立两个单链表,在其中加入控制条件即可。
代码如下:
#include <stdio.h>
#include <malloc.h>
struct node{
int data;
struct node* next;
};
struct node* Createlist(int n){
struct node* head,*tail,*p;
int i,d;
head=(struct node*)malloc(sizeof(struct node));
head->next=NULL;
tail=head;
for(i=1;i<=n;i++){
p=(struct node*)malloc(sizeof(struct node));
scanf("%d",&d);
p->data=d;
p->next=tail->next;
tail->next=p;
tail=p;
}
return head;
};
void Chaifenlist1(struct node* head,struct node* head1,struct node* head2){/*将一个单链表拆分成两个单链表*/
struct node* tail1,*tail2,*p;
int n,m;
n=0;
m=0;
tail1=head1;
tail2=head2;
while(head){
if(head->data%2==0){/*是偶数,建立一个单链表*/
n++;
p=(struct node*)malloc(sizeof(struct node));
p->data=head->data;
p->next=tail1->next;
tail1->next=p;
tail1=p;
}
else{
m++;
p=(struct node*)malloc(sizeof(struct node));
p->data=head->data;
p->next=tail2->next;
tail2->next=p;
tail2=p;
}
head=head->next;
}
printf("%d %d\n",n,m);
for(p=head1->next;p!=NULL;p=p->next){
if(p==head1->next)
printf("%d",p->data);
else
printf(" %d",p->data);
}
printf("\n");
for(p=head2->next;p!=NULL;p=p->next){
if (p==head2->next)
printf("%d",p->data);
else
printf(" %d",p->data);
}
}
int main(){
struct node* head,*p,*head1,*head2;
head=(struct node*)malloc(sizeof(struct node));
head->next=NULL;
head1=(struct node*)malloc(sizeof(struct node));
head1->next=NULL;
head2=(struct node*)malloc(sizeof(struct node));
head2->next=NULL;
int i,n;
scanf("%d",&n);
head=Createlist(n);
p=head->next;
Chaifenlist1(p,head1,head2);
return 0;
}
- 数据结构实验之链表五:单链表的拆分
- 数据结构实验之链表五:单链表的拆分
- 数据结构实验之链表五:单链表的拆分
- 数据结构实验之链表五:单链表的拆分
- 数据结构实验之链表五:单链表的拆分
- 数据结构实验之链表五:单链表的拆分
- 数据结构实验之链表五:单链表的拆分
- 数据结构实验之链表五:单链表的拆分
- 数据结构实验之链表五:单链表的拆分
- 数据结构实验之链表五:单链表的拆分
- 数据结构实验之链表五:单链表的拆分
- 数据结构实验之链表五:单链表的拆分
- 数据结构实验之链表五:单链表的拆分
- 数据结构实验之链表五:单链表的拆分
- 数据结构实验之链表五:单链表的拆分
- 数据结构实验之链表五:单链表的拆分
- 数据结构实验之链表五:单链表的拆分
- 数据结构实验之链表五:单链表的拆分
- UNIX/LINUX 平台可执行文件格式分析
- 区间DP POJ 3661 Running
- JDK、JRE和JVM区别和联系
- GTK+ 图形界面编程--个人总结
- 自定义View学习笔记之自定义圆
- 数据结构实验之链表五:单链表的拆分
- 一次优化web项目的经历记录(二)
- UIView的layoutSubviews和drawRect方法何时调用
- Android如何优雅的销毁多个activity
- booloader编写
- Apache POI(2):单元格(cell)
- AFNetworking框架的几个细节
- 模拟队列
- This is my path of Java!