1 依靠单向循环链表 完成约瑟夫环
主要函数
void jose(int n,int m)
{
Looplink *L=list_create();
for(int i=1;i<=n;i++)
{
list_inisert_tail(L,i);
}
Looplink *S=kill_head(L);
Looplink *q=S;
Looplink *p=NULL;
printf("约瑟夫环结果为\n");
while(1)
{
for(int i=1;i<m;i++)
{
p=q;
q=q->next;
}
printf("\t%d",q->data);
p->next=q->next;
free(q);
if(q->next==q && n==1)
{
q=NULL;
break;
}
q=p->next;
n--;
}
printf("\n");
}
辅助函数
创建单向循环链表函数
Looplink *list_create()
{
Looplink *L=(Looplink *)malloc(sizeof(Looplink));
if(NULL==L)
{
printf("创建失败\n");
return NULL;
}
L->len=0;
L->next=L;
printf("创建成功\n");
return L;
}
判断链表是否为空函数
int list_empty(Looplink *L)
{
if(NULL==L)
{
printf("所给链表不合法\n");
return -1;
}
return L->next==L ?1:0;
}
删除头结点函数
Looplink *kill_head(Looplink *L)
{
if(NULL==L || list_empty(L))
{
printf("删除失败\n");
return NULL;
}
Looplink *q=L->next;
while(q->next!=L)
{
q=q->next;
}
q->next=L->next;
free(L);
L=NULL;
printf("头结点删除成功\n");
return q->next;
}
单向循环链表结构体
typedef int datatype;
typedef struct Node
{
union
{
int len;
datatype data;
};
struct Node *next;
}Looplink;
使用栈的特点完成 十转八的进制转换
主要函数
void d_to_o(int x)
{
int y=x;
seqStack *S=create();
while(x)
{
push(S ,x%8);
x/=8;
}
printf("%d由十进制转换为八进制,结果为:",y);
while(S->top!=-1)
{
printf("%d",S->data[S->top]);
pop(S);
}
printf("\n");
destroy(S);
}
辅助函数
创建栈函数
seqStack *create()
{
seqStack *S=(seqStack *)malloc(sizeof(seqStack));
if(S==NULL)
{
printf("创建失败\n");
return NULL;
}
S->top=-1;
printf("创建成功\n");
return S;
}
判断空函数
int empty(seqStack *S)
{
if(NULL==S )
{
printf("输入的顺序栈不合法\n");
return -1;
}
return S->top==-1 ?1:0;
}
判断满函数
int full(seqStack *S)
{
if(NULL==S )
{
printf("输入的顺序栈不合法\n");
return -1;
}
return S->top==MAX-1 ?1:0;
}
入栈、进栈、压栈函数
int push(seqStack *S ,datatype e)
{
if(NULL==S || full(S))
{
printf("入栈失败\n");
return -1;
}
S->top++;
S->data[S->top]=e;
printf("入栈成功\n");
return 0;
}
出栈、弹栈函数
int pop(seqStack *S)
{
if(NULL==S || empty(S))
{
printf("出栈失败\n");
return -1;
}
S->top--;
return 0;
}
销毁栈函数
void destroy(seqStack *S)
{
if(NULL!=S)
{
free(S);
S=NULL;
printf("栈释放成功\n");
}
}
栈的结构体
#define MAX 30
typedef int datatype;
typedef struct
{
datatype data[MAX];
int top;
}seqStack;