[SDUT] [linked list] 2120 - linked list 5 of data structure experiment: split of single linked list

Problem Description

Input N integers to build a single chain table, and split the single chain table into two sub lists. The first sub list stores all the even numbers and the second sub list stores all the odd numbers. The relative order of data in the two sub linked lists is consistent with the original linked list.

Input

Enter the integer N in the first line;;
Enter N integers in the second line.

Output

The first row outputs the number of elements of even and odd linked list respectively;
The second row outputs all the data of even sub linked list in turn;
The third line outputs all the data of odd sub linked list in turn.

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

Arrays are not allowed!

Source

 

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 #include <algorithm>
 5 
 6 using namespace std;
 7 
 8 struct node
 9 {
10     int data;
11     struct node *next;
12 };
13 
14 int cnt1,cnt2;
15 
16 //Application space
17 struct node *arr_mal(struct node *p)
18 {
19     p = (struct node *)malloc(sizeof(struct node));
20     return p;
21 }
22 
23 //Create linked list
24 void arr_create(struct node *head,int n)
25 {
26     struct node *p=NULL,*tail=NULL;
27     tail = head;
28     while(n--)
29     {
30         p = arr_mal(p);
31         scanf("%d",&p ->data);
32         tail ->next = p;
33         tail = tail ->next;
34     }
35 }
36 
37 //Output linked list
38 void arr_prin(struct node *head)
39 {
40     struct node *p=NULL;
41     p = head ->next;
42     if(p != NULL)
43     {
44         printf("%d",p ->data);
45         p = p ->next;
46     }
47     while(p != NULL)
48     {
49         printf(" %d",p ->data);
50         p = p ->next;
51     }
52     printf("\n");
53 }
54 
55 //split
56 void arr_split(struct node *head1,struct node *head2)
57 {
58 
59     struct node *p1=NULL,*p2=NULL,*tail=NULL;
60     p1 = head1;
61     p2 = head2;
62     while(p1 ->next != NULL)
63     {
64         if(p1 ->next->data%2)
65         {
66             p1 = p1 ->next;
67             cnt1++;
68         }
69         else
70         {
71             tail = p1 ->next;
72             p1 ->next = tail ->next;
73             tail ->next = NULL;
74             p2 ->next = tail;
75             p2 = p2 ->next;
76             cnt2++;
77         }
78     }
79 }
80 
81 int main()
82 {
83     int n;
84     cnt1=cnt2=0;
85     struct node *head1=NULL,*head2=NULL;
86     head1 = arr_mal(head1);
87     head2 = arr_mal(head2);
88     scanf("%d",&n);
89     arr_create(head1,n);
90     arr_split(head1,head2);
91     printf("%d %d\n",cnt2,cnt1);
92     arr_prin(head2);
93     arr_prin(head1);
94     return 0;
95 }

Keywords: C++

Added by altexis on Tue, 10 Dec 2019 19:16:19 +0200