實現將線性表奇數和偶數分開。

 #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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章