编程学习网为您整理以下代码实例,主要实现:C语言拆分循环链表,希望可以帮到各位朋友。
@H_403_0@
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *even = NulL;
struct node *odd = NulL;
struct node *List = NulL;
//Create linked List
voID insert(int data) {
// Allocate memory for new node;
struct node *link = (struct node*) malloc(sizeof(struct node));
struct node *current;
link->data = data;
link->next = NulL;
if(List == NulL) {
List = link;
List->next = link;
return;
}
current = List;
while(current->next != List)
current = current->next;
// Insert link at the end of the List
current->next = link;
link->next = List;
}
voID display(struct node *head) {
struct node *ptr = head;
printf("[head] =>");
//start from the beginning
while(ptr->next != head) {
printf(" %d =>",ptr->data);
ptr = ptr->next;
}
printf(" %d =>",ptr->data);
printf(" [head]\n");
}
voID split_List() {
int count = 0;
// Allocate memory for new node;
struct node *List1;
struct node *link;
struct node *current;
List1 = List;
while(List1->next != List) {
struct node *link = (struct node*) malloc(sizeof(struct node));
link->data = List1->data;
link->next = NulL;
if(List1->data%2 == 0) {
if(even == NulL) {
even = link;
even->next = link;
List1 = List1->next;
continue;
} else {
current = even;
while(current->next != even) {
current = current->next;
}
// Insert link at the end of the List
current->next = link;
link->next = even;
}
List1 = List1->next;
} else {
if(odd == NulL) {
odd = link;
odd->next = link;
List1 = List1->next;
continue;
} else {
current = odd;
while(current->next!= odd) {
current = current->next;
}
// Insert link at the end of the List
current->next = link;
link->next = odd;
}
List1 = List1->next;
}
}
// Lets handle the last node
link = (struct node*) malloc(sizeof(struct node));
link->data = List1->data;
link->next = NulL;
if(List1->data%2 == 0) {
current = even;
while(current->next != even) {
current = current->next;
}
// Insert link at the end of the List
current->next = link;
link->next = even;
} else {
current = odd;
while(current->next!= odd) {
current = current->next;
}
// Insert link at the end of the List
current->next = link;
link->next = odd;
}
}
int main() {
int i;
for(i = 1; i <= 10; i++)
insert(i);
printf("Complete List: \n");
display(List);
split_List();
printf("\nOdd : ");
display(odd);
printf("Even : ");
display(even);
return 0;
}
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!