提示:用環形鏈表實現
對於這個題目其實就是用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;}