把今日学习的循环单链表用在joseph问题上,写段代码保存;
linklist.c 代码如下
#include "linklist.h"
#include <string.h>
linklist list_create()
{
linklist H,r,p;
int n,i;
loop :
printf ("please input n:");
scanf("%d",&n);
if (n < 0)
{
printf("n > 0\n");
goto loop;
}
if ((H = (linklist)malloc(sizeof(listnode)))==NULL)
{
printf("malloc failed\n");
return NULL;
}
H->next = H;
H->data = 1;
r = H;
for (i = 1; i <= n;i++){
if ((p = (linklist)malloc(sizeof(listnode)))==NULL)
{
printf("malloc failed\n");
return NULL;
}
p->data = i;
r->next = p;
r = p;
}
p->next = H;
return H;
}
void joseph(linklist H,int k,int m)
{
int i;
linklist r,p;
r = H;
while (r->next->data!=k)
{
r = r->next;
}
printf ("k=%d\n",k);
while(r->next != r)
{
for (i = 0;i < m-1; i++)
{
r = r->next;
}
p = r->next;
r->next = p->next;
printf("%d ",p->data);
free(p);
p = NULL;
}
}
void list_show(linklist H)
{
linklist p = H;
while (p->next!= H)
{
printf("%d ",p->data);
p = p->next;
}
printf("%d\n",p->data);
}
头文件如下
#ifndef _LINKLIST_H_
#define _LINKLIST_H_#include <stdio.h>
#include <stdlib.h>
typedef int datatype;
typedef struct node{
datatype data;
struct node *next;
}listnode,*linklist;
extern linklist list_create();
extern void list_show(linklist H);
extern void joseph(linklist H,int k,int m);
#endif
test执行文件
#include "linklist.h"
int main(int argc, const char *argv[])
{
linklist H;
int k = 3 , m = 4;
H = list_create();
list_show(H);
joseph(H,k,m);
return 0;
}