fisherro
-
C,
pasted
on Jan 27:
|
#include <stdio.h>
#include <stdlib.h>
typedef struct Snode_tag
{
int data;
struct Snode_tag *next;
} Snode;
void print_single(Snode *head)
{
printf("%d", head->data);
if (head->next) {
printf(", ");
print_single(head->next);
}
}
void print_single_list(Snode *head)
{
if (head) {
print_single(head);
printf("\n");
} else {
printf("NULL\n");
}
}
Snode *make_single(int n)
{
if (0 == n) return NULL;
Snode *node = malloc(sizeof(Snode));
if (!node) return NULL;
node->data = n;
node->next = make_single(n - 1);
return node;
}
//Put the even nodes of head into first.
//Put the odd nodes of head in second.
void split_single(Snode *head, Snode **first, Snode **second)
{
if (!head) return;
Snode *f = head;
Snode *s = head->next;
if (s) {
f->next = s->next;
if (f->next) {
s->next = f->next->next;
split_single(f->next, NULL, NULL);
}
}
if (first) *first = f;
if (second) *second = s;
}
int main()
{
Snode *list = make_single(12);
print_single_list(list);
Snode *first = NULL;
Snode *second = NULL;
split_single(list, &first, &second);
print_single_list(first);
print_single_list(second);
return 0;
}
|
Output:
|
12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
12, 10, 8, 6, 4, 2
11, 9, 7, 5, 3, 1
|
|