日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

约瑟夫环(杀人游戏)

發布時間:2023/12/10 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 约瑟夫环(杀人游戏) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

問題描述:

剛學數據結構的時候,我們可能用鏈表的方法去模擬這個過程,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個節點,刪除一個節點,需要注意的是刪除節點前,要記錄下一個節點的位置,所以要定義兩個指針變量,一個指向當前節點,另一個指向當前節點的前一個節點,
  • 刪除節點節點前,記錄要刪除節點的下一個節點的位置
  • 刪除節點后當前節點指向刪除節點的下一個節點
prenode->next = curnode->next;printf("%d\t", curnode->data);free(curnode);curnode = prenode->next;

完整代碼

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

總結

以上是生活随笔為你收集整理的约瑟夫环(杀人游戏)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。