資料結構實驗之鏈表五:單鏈表的拆分
Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic
Problem Description
輸入N個整數順序建立一個單鏈表,將該單鏈表拆分成兩個子鏈表,第一個子鏈表存放了所有的偶數,第二個子鏈表存放了所有的奇數。兩個子鏈表中資料的相對次序與原鏈表一致。
Input
第一行輸入整數N;;
第二行依次輸入N個整數。
Output
第一行分別輸出偶數鏈表與奇數鏈表的元素個數;
第二行依次輸出偶數子鏈表的所有資料;
第三行依次輸出奇數子鏈表的所有資料。
Example Input
10
1 3 22 8 15 999 9 44 6 1001
Example Output
4 6
22 8 44 6
1 3 15 999 9 1001
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
int main()
{
int n,a = 0, b = 0;
struct node *head, *head1, *head2, *p, *q, *t1, *t2;
scanf("%d", &n);
head = (struct node*)malloc(sizeof(struct node));
head1 = (struct node*)malloc(sizeof(struct node));
head2 = (struct node*)malloc(sizeof(struct node));
head -> next = NULL;
head2 -> next = NULL;
head1 -> next = NULL;
q = head;
while(n--)
{
p = (struct node*)malloc(sizeof(struct node));
scanf("%d", &p -> data);
q -> next = p;
q = p;
}
p = head -> next;
q = p -> next;
head -> next = NULL;
t1 = head1; t2 = head2;
while(p != NULL)
{
if(p -> data % 2 == 0)
{
t1 -> next = p;
t1 = p;
a++;
}
else
{
t2 -> next = p;
t2 = p;
b++;
}
p = q;
if(q != NULL)
q = q -> next;
}
p = head1 -> next;
q = head2 -> next;
printf("%d %d\n", a, b);
while(p != NULL)
{
printf("%d", p -> data);
if(p -> next != NULL)
printf(" ");
else
printf("\n");
p = p -> next;
}
while(q != NULL)
{
printf("%d", q -> data);
if(q -> next != NULL)
printf(" ");
else
printf("\n");
q = q -> next;
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/64543.html
標籤:基礎類
