#头文件
#ifndef __YSF_H__
#define __YSF_H__
typedef int datatype;
typedef struct node
{
union
{
datatype data;
int len;
};
struct node *next;
}node, *Looplist;
Looplist create();//创建
Looplist make_code(datatype e);//创建元素
int insert_head(Looplist l,datatype e);//标准头插
int insert_tail(Looplist l,datatype e);//尾插(可无头)
Looplist delete_first(Looplist l);//删除头节点
void show(Looplist l);//遍历
void show_nohead(Looplist l);//删除头节点后的遍历
Looplist Johnsph(Looplist l);//约瑟夫环
#endif
自定义函数
#include "ysf.h"
#include <stdlib.h>
#include <stdio.h>
Looplist create()//创建
{
Looplist l=(Looplist)malloc(sizeof(node));
if(NULL==l)
{
puts("Fail to create\n");
return NULL;
}
l->len=0;
l->next=l;
return l;
}
Looplist make_code(datatype e)//创建元素
{
Looplist p=(Looplist)malloc(sizeof(node));
if(NULL==p)
{
puts("Fail to make\n");
return NULL;
}
p->data=e;
p->next=NULL;
return p;
}
int insert_head(Looplist l,datatype e)//头插
{
if(NULL==l)
{
puts("Fail to insert_head\n");
return -1;
}
Looplist p=make_code(e);
p->next=l->next;
l->next=p;
l->len++;
puts("suc to insert_head\n");
return 0;
}
int insert_tail(Looplist l,datatype e)//尾插
{
if(NULL==l)
{
puts("Fail to insert_tail\n");
return -1;
}
Looplist p=l;
while(p->next!=l)
{
p=p->next;
}
Looplist p_new=make_code(e);
p_new->next=p->next;
p->next=p_new;
l->len++;
puts("suc to insert_tail\n");
return 0;
}
Looplist delete_first(Looplist l)
{
if(NULL==l)
{
puts("Fail to delete_first\n");
return NULL;
}
Looplist p=l;
while(p->next!=l)
{
p=p->next;
}
p->next=l->next;
free(l);
l=NULL;
return p->next;
}
void show_nohead(Looplist l)
{
if(NULL==l)
{
puts("Fail to show_nohead\n");
return;
}
Looplist p=l;
do{
printf("%d\t",p->data);
p=p->next;
}while(p!=l);
putchar(10);
}
void show(Looplist l)
{
if(NULL==l)
{
puts("Fail to show\n");
return;
}
Looplist p=l->next;
while(p!=l)
{
printf("%d\t",p->data);
p=p->next;
}
putchar(10);
}
Looplist Johnsph(Looplist l)
{
Looplist p_new=create();
Looplist p=l;
Looplist current=NULL;
while(p->next!=p)
{
for(int i=1;i<3;i++)
{
p=p->next;
}
current = p->next;
insert_tail(p_new,current->data);
p->next=current->next;
p=p->next;
free(current);
current=NULL;
//l->len--; //问题所在,原因不详
//p_new->len++;
}
insert_tail(p_new,p->data);
return p_new;
}
主函数
#include "ysf.h"
#include <stdlib.h>
#include <stdio.h>
int main(int argc, const char *argv[])
{
Looplist l=create();
insert_head(l,1);
insert_tail(l,2);
insert_tail(l,3);
insert_tail(l,4);
insert_tail(l,5);
insert_tail(l,6);
insert_tail(l,7);
insert_tail(l,8);
show(l);
l=delete_first(l);
show_nohead(l);
Looplist n=Johnsph(l);
show(n);
return 0;
}
现象
4 8 5 2 1 3 7 6