约瑟夫环(杀人游戏)
生活随笔
收集整理的這篇文章主要介紹了
约瑟夫环(杀人游戏)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
問題描述:
剛學數據結構的時候,我們可能用鏈表的方法去模擬這個過程,N個人看作是N個鏈表節點,節點1指向節點2,節點2指向節點3,……,節點N - 1指向節點N,節點N指向節點1,這樣就形成了一個環。然后從節點1開始1、2、3……往下報數,每報到M,就把那個節點從環上刪除。下一個節點接著從1開始報數。最終鏈表僅剩一個節點。它就是最終的勝利者。
舉例:某天你去原始森林玩,碰到了一群土著邀請你去玩一個殺人游戲8個人圍坐一圈,報數,報到3的人拿根繩吊死,問如何保命,笑到最后
思路分析:
該問題可以抽象為一個無頭節點單向循環鏈表,鏈表中有8個節點,各節點中依次填入數據1,2,3,4,5,6,7,8
- 初始時刻,頭指針指向1所在的節點
- 每隔2個節點,刪除一個節點,需要注意的是刪除節點前,要記錄下一個節點的位置,所以要定義兩個指針變量,一個指向當前節點,另一個指向當前節點的前一個節點,
- 刪除節點節點前,記錄要刪除節點的下一個節點的位置
- 刪除節點后當前節點指向刪除節點的下一個節點
完整代碼
main.c(用于測試)
#include<stdio.h> #include<stdlib.h> #include "list.h"int main() {struct node_st *list = NULL,*lastnode =NULL;list=list_create(SIZE);list_show(list);list_kill(&list, STEP);list_show(list);return 0; }list.c(用于函數定義)
#include<stdio.h> #include<stdlib.h> #include "list.h"//約瑟夫環可以使用無頭節點,單向循環鏈表來表示 struct node_st* list_create(int n) {int i = 1;struct node_st* p = NULL;struct node_st* ps = NULL;struct node_st* q = NULL;p = (struct node_st*)malloc(sizeof(struct node_st));if (p == NULL){return NULL;}p->data = i;p->next = p;i++;//定義一個結構體變量,記錄約瑟夫環起始位置ps = p;while (i <= n){q = (struct node_st*)malloc(sizeof(struct node_st));if (q == NULL){return NULL;}q->data = i;q->next = ps;p->next = q;p = q;i++;}return ps; }void list_show(struct node_st* ps) {//一般來講,我們不移動頭指針ps,而是移動ps的拷貝,原因://出錯時方便調試以及頭指針位置不丟失struct node_st* p = NULL;for (p = ps; p->next != ps; p = p->next){printf("%d\t", p->data);}printf("%d\n", p->data); }void list_kill(struct node_st** ps,int n) {struct node_st *prenode = NULL;struct node_st *curnode = *ps;int i = 0;while (curnode != curnode->next){//每輪刪除,隔n-1個節點,刪除一個節點while (i < n - 1){prenode = curnode;curnode = curnode->next;i++;}prenode->next = curnode->next;printf("%d\t", curnode->data);free(curnode);curnode = prenode->next;i = 0;}*ps = curnode;printf("\n");}list.h(負責函數聲明)
#ifndef LIST_H__ #define LIST_H__ #define SIZE 8 #define STEP 3 struct node_st {int data;struct node_st *next; }; //約瑟夫環的創建 struct node_st* list_create(int n); //約瑟夫環的展示 void list_show(struct node_st*ps); //約瑟夫環刪除節點 void list_kill(struct node_st** ps,int n); #endif總結
以上是生活随笔為你收集整理的约瑟夫环(杀人游戏)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一文讲懂什么是vlan、三层交换机、网关
- 下一篇: mybatis-plus 查询,删除