提示:用環形鏈表實現
對於這個題目其實就是用c語言的循環鏈表實現一個約瑟夫環。我們可以定義一個循環鏈表,將這n個人加入到鏈表中,然后定義三個節點指針在鏈表上循環,移動跨度為3,利用鏈表的循環功能每次刪除第三個節點,這邊要注意的一個問題就是你定義的是3個指針,且在循環中他們彼此也都是有
->next關系,一般我們判斷循環結束條件時都是一個節點的下一個節點是否為它本身(如ptr->next == ptr),這里我們要注意循環體中鏈接方向否則很可能出現無用指針導致錯誤,因為最后我們要剩下一個節點那么ptr->next為NULL,而剩下的不能是NULL->next.
具體程序,如下:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int num;
struct node *next;
};
struct node *head;
struct node *last;
void cre_list()
{
head = (struct node *)malloc(sizeof(struct node));
last = head;
head->next = head;
}
void display_node()
{
struct node *ptr = head->next;
while(ptr != head)
{
printf("%d\t",ptr->num);
ptr = ptr->next;
}
printf("\n");
}
void add_node(int num)
{
struct node *ptr = (struct node *)malloc(sizeof(struct node));
ptr->num = num;
ptr->next = head;
last->next = ptr;
last = ptr;
}
void rev_node()
{
struct node *ptr = head;
last->next = head->next;
head = head->next;
free(ptr);
}
void tiren_node()
{
struct node *ptr = head;
struct node *str = ptr->next;
struct node *qtr = str->next;
while(ptr->next != ptr)
{
str = ptr->next;
qtr = str->next;
str->next = qtr->next;
ptr = str->next;
}
printf("%d\n",ptr->num);
}
int main()
{
int i = 0;
cre_list();
int n;
printf("please input n:\n");
scanf("%d",&n);
printf("%d\n",n);
for(i = 1;i <= n;i++)
{
add_node(i);
}
display_node();
rev_node();
tiren_node();
return 0;
}