資料結構實驗之連結清單五:單連結清單的拆分
Time Limit: 1000 ms Memory Limit: 65536 KiB
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
不得使用數組!
**提示:**所謂的拆分連結清單,就是按照題目要求,根據對輸入的數進行判斷,建多個連結清單的過程
AC代碼:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
int main()
{
int t,x,n=0,m=0;
struct node *head,*tou,*p,*q,*r,*k;
head=(struct node *)malloc(sizeof(struct node));//偶數連結清單的頭指針
head->next=NULL;
q=head;
tou=(struct node *)malloc(sizeof(struct node));//奇數連結清單的頭指針
tou->next=NULL;
r=tou;
scanf("%d",&t);
while(t--)//區分奇、偶數,分别順序建連結清單
{
scanf("%d",&x);
if(x%2==0)
{
p=(struct node *)malloc(sizeof(struct node));
p->data=x;
p->next=NULL;
q->next=p;
q=p;
n++;
}
else
{
k=(struct node *)malloc(sizeof(struct node));
k->data=x;
k->next=NULL;
r->next=k;
r=k;
m++;
}
}
q=head->next;
printf("%d %d\n",n,m);
while(q)
{
if(q->next==NULL) printf("%d\n",q->data);
else printf("%d ",q->data);
q=q->next;
}
r=tou->next;
while(r)
{
if(r->next==NULL) printf("%d\n",r->data);
else printf("%d ",r->data);
r=r->next;
}
return 0;
}
餘生還請多多指教!