#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}node;
void create_list(node **head)
{
int a;
node *p;
*head=(node *)malloc(sizeof(node));
(*head)->next=NULL;
printf("Input numbers,end by -1:");
scanf("%d",&a);
while(a!=-1)
{
p=(node *)malloc(sizeof(node));
p->data=a;
p->next=(*head)->next;
(*head)->next=p;
scanf("%d",&a);
}
}
void print_list(node *head)
{
node *p;
p=head->next;
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
}
void depart(node *head,node **even,node **odd)
{
node *p,*q;
*even=(node *)malloc(sizeof(node));
*odd=(node *)malloc(sizeof(node));
(*even)->next=NULL;
(*odd)->next=NULL;
p=head->next;
while(p!=NULL)
{
q=p;
p=p->next;
if(q->data%2==0)
{
q->next=(*even)->next;
(*even)->next=q;
}
else
{
q->next=(*odd)->next;
(*odd)->next=q;
}
}
}
int main()
{
node *head,*odd,*even;
create_list(&head);
print_list(head);
depart(head,&even,&odd);
printf("/neven:");
print_list(even);
printf("/nodd:");
print_list(odd);
printf("/n");
return 0;
}
本文介绍了一个使用C语言实现的链表数据结构,包括创建链表、打印链表元素及按奇偶数分离链表的功能。通过具体代码展示了如何动态分配内存来构建链表节点,并实现了读取用户输入的一系列整数构建链表,最后将链表中的节点按数据的奇偶性分为两个独立的链表。

1万+

被折叠的 条评论
为什么被折叠?



