#include <stdio.h>
#include <stdlib.h>
typedef int datatype;
typedef struct node
{
datatype data;
struct node *
next;
}linklist,*
linklist_p;
linklist_p create_linked();
int insert_head(linklist_p L,datatype value);
void show_list(linklist_p L);
int del_head(linklist_p L);
int insert_order(linklist_p L,datatype value);
int del_order(linklist_p L,datatype value);
void joseph_game(linklist_p L,datatype k,datatype m);
int main(
int argc,
const char *
argv[])
{
linklist_p L =
create_linked();
if(NULL ==
L)
{
printf("函数调用失败\n");
return -
1;
}
//insert_order(L,2);
//insert_order(L,3);
//insert_order(L,4);
//show_list(L);
del_order(L,
4);
insert_head(L,8);
insert_head(L,7);
insert_head(L,6);
insert_head(L,5);
insert_head(L,4);
insert_head(L,3);
insert_head(L,2);
show_list(L);
joseph_game(L,3,
4);
return 0;
}
linklist_p create_linked()
{
linklist_p L =(linklist_p) malloc(
sizeof(linklist));
if(NULL ==
L)
{
printf("内存开辟失败\n");
return NULL;
}
L->next =
L;
L->data =
1;
return L;
}
int insert_head(linklist_p L,datatype value)
{
linklist_p p = (linklist_p)malloc(
sizeof(linklist));
if(p ==
NULL)
{
printf("内存开辟失败\n");
return -
1;
}
p->next = L->
next;
L->next =
p;
p->data =
value;
return 0;
}
void show_list(linklist_p L)
{
linklist_p p =
L;
while(p->next !=
L)
{
printf("%d",p->
data);
p = p->
next;
}
printf("%d\n",p->
data);
}
int del_head(linklist_p L)
{
if(L==
NULL)
{
printf("链表为空\n");
return -
1;
}
linklist_p p = L->
next;
L->next = p->
next;
free(p);
p =
NULL;
return 0;
}
int insert_order(linklist_p L,datatype value)
{
linklist_p p =NULL, q =
L;
while(q->next!=L && q->next->data <=
value)
{
q = q->
next;
}
if((p=(linklist_p)malloc(
sizeof(linklist))) ==
NULL)
{
printf("分配地址失败\n");
return -
1;
}
p->data =
value;
p->next = q->
next;
q->next =
p;
return 0;
}
int del_order(linklist_p L,datatype value)
{
linklist_p p = L,q =
NULL;
while(p->next!=
L)
{
if(p->next->data ==
value)
{
q = p->
next;
p->next = q->
next;
free(q);
q =
NULL;
return 1;
}
p = p->
next;
}
return 0;
}
//约瑟夫问题
void joseph_game(linklist_p L,datatype k,datatype m)
{
linklist_p p = L,q =
NULL;
int i,j;
//本来应该循环k-1次,因为后面第二循环首次循环m-2,后续每次循环m-1,所以在第一次循环少循环一次,以弥补第二个循环的首次循环
for(i =
0; i < k-
2; i++
)
{
p = p->
next;
}
while(p->next !=
p)
{
for(i =
0; i < m-
1; i++
)
{
p = p->
next;
}
q = p->
next;
p -> next = q->
next;
printf("%d",q->
data);
free(q);
q =
NULL;
}
printf("%d\n",p->
data);
}
转载于:https://www.cnblogs.com/billcharint/p/10724559.html