/*
* single.h
*
* Created on: 2012-7-21
* Author: root
*/
#ifndef SINGLE_H_
#define SINGLE_H_
#include<stdio.h>
#include<stdlib.h>
#define TURE 1
#define FALSE 0
typedef struct link{
int data;
struct link *next;
}Link,*pLink;
pLink CreateLink(); //声明创建单向循环链表的函数
void PrintLink(pLink H,int no); //声明打印单向循环链表的函数
pLink CatLink(pLink H,pLink S); //声明连接两个单向循环链表的函数
pLink GetLink(pLink H,int addr); //声明给定位置返回该位置节点的函数
void Josephu(pLink H,int n,int local,int no); //约瑟夫函数的声明
#endif /* SINGLE_H_ */
/*
* main.c
*
* Created on: 2012-7-21
* Author: root
*/
#include"single.h"
int main()
{
#if 0 //创建单向循环链表
pLink H;
H = CreateLink(); //create a link;
#endif
#if 0
int numb; //打印该循环链表 numb为打印次数
printf("\nplease input the times of print:");
scanf("%d",&numb);
PrintLink(H,numb);
#endif
#if 0 //给定位置返回该位置在链表中的节点
pLink s ;
int addr;
printf("\nplease input the addr you want to get:");
scanf("%d",&addr);
s = GetLink(H,addr);
printf("%d\n",s->data);
#endif
#if 0
pLink temp,S; //两个单向循环链表的连接
S = CreateLink();
temp = CatLink(H,S);
printf("\nplease input the times of print:");
scanf("%d",&numb);
PrintLink( temp,numb);
#endif
#if 0
int i = 0,numb;
printf("\nplease input the times of print:");
scanf("%d",&numb);
#endif
#if 0
int addr,numb; //addr表示从第几个位置开始 numb表示约定数
printf("\nplease input the frist addr:");
scanf("%d",&addr);
printf("\nplease input the times:");
scanf("%d",&numb);
Josephu(H,9,addr,numb); // 9 表示参加约瑟夫环的人数
#endif
return 0;
}
/*
* single.c
*
* Created on: 2012-7-21
* Author: root
*/
#include"single.h"
#if 0
pLink CreateLink() //create the list 创建新链表
{
pLink r ,H;
H = NULL;
int a;
printf("please input numb:");
scanf("%d",&a);
while(a != -1)
{
pLink new=(pLink)malloc(sizeof(Link));
new->data = a;
new->next = NULL;
if(H == NULL)
{
H = new;
r = H;
}
else{
r->next= new;
r = r->next;
}
printf("please input numb:");
scanf("%d",&a);
}
r->next = H; //创建单向循环链表的关键
return H;
}
#endif
#if 0
void PrintLink(pLink H,int no) //print the list 打印链表
{
pLink r = H;
int i;
for(i = 0;i < no;i++)
{
printf("%d\t",r->data);
r=r->next;
}
printf("\n");
}
#endif
#if 0
pLink GetLink(pLink H,int addr){
pLink p=H;
int i;
for(i = 1;i< addr;i++)
{
p = p->next;
}
return p;
}
#endif
#if 0
#endif
#if 0
pLink CatLink(pLink H,pLink S){
pLink p1,p2,r1,r2;
p1 = H;
p2 = H->next;
r1 = S;
r2 = S->next;
H->next = NULL;
S->next = NULL;
p1->next = r2;
r1->next = p2;
return p1;
}
#endif
#if 0
void Josephu(pLink H,int n,int local,int no){
int i ;
pLink s = GetLink(H,local-1);
pLink p, r ;
while(s!=s->next){
r = s;
for(i= 1;i<= no-1;i++)
{
r= r->next;
}
s = r->next;
p = s->next;
r->next = p;
printf("%d\t",s->data);
free(s);
s = r;
}
printf("%d",s->data);
printf("\n");
}
#endif
单向循环链表的应用代表之一就是约瑟夫环的实现
Josephu问题:设编号分别为:1,2,…,n的n个人围坐一圈。约定序号为k(1≤k≤n)的人从1开始计数,数到m的那个人出列,他的下一位又从1开始计数,数到m的那个人又出列,依次类推,直到所有人出列为止