数据结构实验之链表五:单链表的拆分
Time Limit: 1000 ms Memory Limit: 65536 KiB
Submit Statistic
Problem Description
输入N个整数顺序建立一个单链表,将该单链表拆分成两个子链表,第一个子链表存放了所有的偶数,第二个子链表存放了所有的奇数。两个子链表中数据的相对次序与原链表一致。
Input
第一行输入整数N;;
第二行依次输入N个整数。
Output
第一行分别输出偶数链表与奇数链表的元素个数;
第二行依次输出偶数子链表的所有数据;
第三行依次输出奇数子链表的所有数据。
Sample Input
10
1 3 22 8 15 999 9 44 6 1001
Sample Output
4 6
22 8 44 6
1 3 15 999 9 1001
Hint
不得使用数组!
#include <stdio.h>
#include <stdlib.h>
int n;
struct node
{
int data;
struct node *next;
};
struct node* create(int n)
{
struct node*head, *t;
head = (struct node*)malloc(sizeof(struct node));
head->next = NULL;
t = head;
while(n--)
{
struct node*p;
p = (struct node*)malloc(sizeof(struct node));
p->next = NULL;
scanf("%d", &p->data);
t->next = p;
t = p;
}
return head;
}
void show(struct node*head)
{
struct node *p;
p = head->next;
while(p)
{
printf("%d%c", p->data, p->next==NULL? '\n': ' ');
p = p->next;
}
return;
}
void f(struct node*head)
{
int x=0, y=0;
struct node*p, *head2, *t1, *t2, *head1, *q1, *q2;
head2 = (struct node*)malloc(sizeof(struct node));
head1 = (struct node*)malloc(sizeof(struct node));
head2->next = NULL;
head1->next = NULL;
t1 = head1;
t2 = head2;
p = head->next;
while(p)
{
if(p->data % 2==0)
{
x++;
q1 = (struct node *)malloc(sizeof(struct node));
q1->next = NULL;
q1->data = p->data;
t2->next = q1;
t2 = q1;
}
else
{
y++;
q2 = (struct node *)malloc(sizeof(struct node));
q2->next = NULL;
q2->data = p->data;
t1->next = q2;
t1 = q2;
}
p = p->next;
}
printf("%d %d\n", x, y);
show(head2);
show(head1);
return;
}
int main()
{
scanf("%d",&n);
struct node *head;
head = create(n);
f(head);
return 0;
}
/***************************************************
User name: jk160532姜兴友
Result: Accepted
Take time: 0ms
Take Memory: 148KB
Submit time: 2017-10-08 15:03:13
****************************************************/