一般說來,學習數(shù)據(jù)結構遇伞,都會寫一個約瑟夫環(huán)的算法沛豌?下面我就簡單說說,
對于這個規(guī)則就不細述了赃额。
分析:1 .首先要創(chuàng)建鏈表加派,創(chuàng)建一個循環(huán)鏈表?是要頭結點呢跳芳? 其實都可以
2 .整個實現(xiàn)過程其實就是循環(huán)鏈表的刪除操作芍锦。但是要把握細節(jié)。廢話不多說
便于測試飞盆,我就把密碼寫成了隨機數(shù)
具體的細節(jié)我就寫在注釋里面了
#define _CRT_SECURE_NO_WARNINGS //預編譯處理
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
typedef struct node // 定義節(jié)點
{
int num; //編號
int pwd; //密碼
struct node *next;
}Node, *LinkList;
void CreatList(LinkList &L, int n) // 創(chuàng)建鏈表
{
int data;
LinkList LNew, pCur;
pCur = L;
int i;
srand((unsigned)time(NULL));
for (i = 0; i < n; i++) {
LNew = (LinkList)malloc(sizeof(Node));
LNew->num = i + 1;
LNew->pwd = (rand() % 5 + 1);
pCur->next = LNew;
pCur = LNew;
}
pCur->next = L->next;
return;
}
void Print(LinkList L) // 打印鏈表
{
if (L->next == NULL) { //判斷空鏈表
printf("此鏈表為空娄琉!\n");
return;
}
LinkList pCur;
pCur = L->next;
while (1) {
printf("%-4d%-4d\n", pCur->num, pCur->pwd);
pCur = pCur->next;
if (pCur == L->next)
break;
}
return;
}
void Game(LinkList &L, int n)
{
int count_All; //計數(shù)器,用于標記當前的個數(shù)
int count_Every; //單次循環(huán)計數(shù)器
LinkList pPre;
LinkList FreeTemp;
count_All = 0;
count_Every = 1;
int flagPwd;
srand((unsigned)time(NULL)); /* 設置初始密碼為隨機值(1~n) */
flagPwd = rand()%n+1;
pPre = L;
printf("初始密碼為:flagPwd=%d\n", flagPwd);
while (1) {
if (flagPwd == count_Every) {
printf("%d ", pPre->next->num); //打印 出局者 的序號
printf("%d\n", pPre->next->pwd); // 打印 出局者 的 pwd
flagPwd = pPre->next->pwd; //重置密碼 pwd 為 出局者密碼
FreeTemp = pPre->next; // 記錄出局者 待后續(xù)釋放空間
pPre->next = pPre->next->next; //刪除節(jié)點(出局者)
free(FreeTemp); //釋放出局者
count_All++; //計數(shù) 刪除節(jié)點的個數(shù)
count_Every = 0; // 刪除節(jié)點之后吓歇,計數(shù)為置為 0
}
else {
pPre = pPre->next; //游標后移
}
count_Every++; //當前計數(shù)加 +1
if (count_All == n) {
L->next = NULL;
break;
}
fflush(stdin); //清除緩存
}
}
int main() //主函數(shù)
{
LinkList L; //
L = (LinkList)malloc(sizeof(Node));
L->next = NULL; //頭結點指針域為空孽水,防止為合并之后為空的輸出異常
int n; //游戲人數(shù)
printf("請輸入游戲人數(shù):");
scanf("%d", &n);
CreatList(L, n); //初始化游戲
printf("游戲初始化結果:\n");
Print(L); //打印初始化結果
printf("游戲結果:\n"); //游戲處理
Game(L, n);
//printf("結果:\n");
//Print(L);
system("pause");
return 0;
}
Paste_Image.png