//1.0 将奇数链和偶数链先拆分出来,然后合并
#include<stdio.h>
#include<stdlib.h>
#define N 8
typedef struct node{
int data;
struct node *next;
}ElemSN;
ElemSN *Createlink(int a[])
{
ElemSN *h=NULL,*np;
for(int i=N-1;i>=0;i--)
{//逆向建链
np=(ElemSN *)malloc(sizeof(ElemSN));
np->data=a[i];
np->next=h;
h=np;
}
return h;
}
ElemSN *SortTheOddbeginEven(ElemSN *head)
{
ElemSN *h=NULL,*p,*q,*pk,*t;
p=head;
while(p)
{
if(p->data%2){//数据域值是奇数
pk=p;
if(p==head)
{
p=head=head->next;//此时head为偶数链头指针
}
else{
q->next=p->next;//挂链
p=q->next;//指针p后移
}
//头插
pk->next=h; //奇数链
h=pk;//指针h跟随 及每次头插到h所指结点之前
}
else{//不是奇数,两指针联动
q=p;
p=p->next;
}
}
//跑完后产生两条链,合并两条链表
for(t=h;t->next;t=t->next);
t->next=head;
return h;
}
void Printlink(ElemSN *head)
{
ElemSN *p;
for(p=head;p;p=p->next){
printf("%d",p->data);
}
}
int main()
{
int i;
int *a;
ElemSN *head=NULL;
a=(int *)malloc(N*sizeof(int));
printf("Please input a[i]:");
fo/r(i=0;i<N;i++)
{
scanf("%d",a+i);
}
//创建链表
head=Createlink(a);
//调用函数
head=SortTheOddbeginEven(head);
//输出链表
Printlink(head);
return 0;
}
//2.0 不断头插
#include<stdio.h>
#include<stdlib.h>
#define N 8
typedef struct node{
int data;
struct node *next;
}ElemSN;
ElemSN *Createlink(int *a)
{
ElemSN *h=NULL,*np;
for(int i=N-1;i>=0;i--)
{//逆向建链
np=(ElemSN *)malloc(sizeof(ElemSN));
np->data=a[i];
np->next=h;
h=np;
}
return h;
}
ElemSN *SortTheOddbeginEven(ElemSN *head)
{
ElemSN *p,*q,*h;
h=q=head;
p=head->next;
while(p)
{
if(p->data%2){//是奇数,挂链,挪动指针
q->next=p->next;
p->next=h;//指针p指向要被头插的结点
h=p;//指针h指向的结点作为头插的位置
p=q->next;//指针后移继续判断
}
else{//不是则联动跑
q=p;
p=p->next;
}
}
return h;
}
void Printlink(ElemSN *head)
{
ElemSN *p;
for(p=head;p;p=p->next){
printf("%d",p->data);
}
}
int main()
{
int i;
int *a;
ElemSN *head=NULL;
a=(int *)malloc(N*sizeof(int));
printf("Please input a[i]:");
for(i=0;i<N;i++)
{
scanf("%d",a+i);
}
//创建链表
head=Createlink(a);
//调用函数
head=SortTheOddbeginEven(head);
//输出链表
Printlink(head);
return 0;
}