head.h
#ifndef __head_h__
#define __head_h__
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int datatype;
typedef struct node
{
union
{
int len;
datatype data;
};
struct node *next;
}*Looplink,Node;
Looplink CreateHead();
Looplink CreateNode();
void InserHead(Looplink L,datatype e);
void DeleteByhead(Looplink L);
void InserBybear(Looplink L, datatype e);
void DeleteByBear(Looplink L);
void ShowLooplink(Looplink L);
//约瑟夫环
void josepho(Looplink L,int n);
//void ReveData(Looplink L);
#endif
text.h
#include "head.h"
//单循环头创建
Looplink CreateHead()
{
Looplink L=(Looplink)malloc(sizeof(Node));
if(L==NULL)
return NULL;
L->len=0;
L->next=L;
return L;
}
//普通节点
Looplink CreateNode()
{
Looplink p=(Looplink)malloc(sizeof(Node));
if(p==NULL)
return NULL;
p->data=0;
p->next=NULL;
return p;
}
//从头插入
void InserHead(Looplink L,datatype e)
{
if(L==NULL)
return;
Looplink p=CreateNode();
if(p==NULL)
return;
p->data=e;
p->next=L->next;
L->next=p;
L->len++;
}
//输出效果
void ShowLooplink(Looplink L)
{
Looplink p=L;
while(p->next!=L)
{
p=p->next;
printf("%d\t",p->data);
}
printf("\n");
}
//尾部插入
void InserBybear(Looplink L,datatype e)
{
if(L==NULL)
{
printf("插入数百\n");
return;
}
Looplink q=CreateNode();
if(q==NULL)
{
printf("创建失败\n");
return;
}
q->data=e;
Looplink p;
p=L->next;
while(p->next!=L)
{
p=p->next;
}
q->next=p->next;
p->next=q;
L->len++;
}
//头删
void DeleteByhead(Looplink L)
{
if(L==NULL)
{printf("删除失败\n");
return;
}
if(L->next==L)
return;
Looplink p;
p=L->next;
L->next=p->next;
free(p);
p==NULL;
L->len--;
}
//尾删
void DeleteByBear(Looplink L)
{
if(L==NULL)
{printf("删除失败\n");
return;
}
if(L->next==L)
return;
Looplink p;
p=L;
while(p->next->next!=L)
{
p=p->next;
}
free(p->next);
p->next=L;
L->len--;
}
//约瑟夫环
void josepho(Looplink L,int n)
{
int i,j;
Looplink p=L;
Looplink q;
j=L->len;
for(1;j>0;j--)
{
for(i=0;i<n-1;i++)
{
p=p->next;
if(p==L)
i++;
}
q=p->next;
if(q==L)
q=q->next;
p->next=q->next;
printf("%d\t",q->data);
free(q);
q=NULL;
L->len--;
}
printf("\n");
p=NULL;
}
//排序
/*void ReveData(Looplink L)
{
Looplink p,q;
p=L->next;
int i,j,z=0;
for(i=0;i<L->len-1;i++)
{
for(j=0;j<(L->len-1-i);j++)
{
if((p->data)>(p->next->data))
{
q=p->next;
p->next=q->next;
q->next=p;
p=q;
};
p=p->next;
z++;printf("%d次",z);
}
}
}
*/
main.c
#include "head.h"
int main(int argc, const char *argv[])
{
Looplink L=CreateHead();
if(L==NULL)
{
printf("创建失败\n");
return -1;
}
//头插入
printf("从头输入函数\n");
datatype e;
for(int i=0;i<9;i++)
{
scanf("%d",&e);
InserHead(L,e);
}
ShowLooplink(L);
//头删除
printf("从头部删除后\n");
DeleteByhead(L);
ShowLooplink(L);
//尾插入
printf("输入尾插入元素\n");
scanf("%d",&e);
InserBybear(L,e);
ShowLooplink(L);
//尾删除
DeleteByBear(L);
printf("尾部删除后\n");
ShowLooplink(L);
//第几个位置插入
//排序
//ReveData(L);
//ShowLooplink(L);
//约瑟夫环
int n;
printf("输出去除间隔\n");
scanf("%d",&n);
josepho(L,n);
free(L);
L==NULL;
}