链表结尾

`#include<stdio.h>

include<stdlib.h>

include"joseph.h"

void initJoseph(Joseph_t* game,int n) {
node_t* node = NULL;//新节点
for (int i = 1; i <= n; i++) {
node = malloc(sizeof(node_t));
node->val = i;

	//犯了基础错误,if条件判断“==”
	if (game->head == NULL) {
		game->head = game->tail=node;
	}
	else {
		game->tail->next = node;
		game->tail = node;
	}
	game->tail->next = game->head;
}

}

void startJoseph(Joseph_t* game, int m) {
node_t* pre = NULL;
node_t* cur = game->head;
while (cur->next != cur) {
//报数
pre = cur;//pre备份
for (int i = 1; i < m; i++) {
pre = cur;
cur = cur->next;
}
//删除
pre->next = cur->next;
free(cur);
cur = pre->next;//下次从哪里开始
}
printf("只剩下:%d\n", cur->val);

}

//void startJoseph(Joseph_t* game, int m) {
// node_t* pre = NULL;
// node_t* cur = game->head;
//
// //只剩下一个数就停止
// while (cur->next != cur) {
// //报数
// pre = cur;
// for (int i = 1; i < m; ++i) {
// pre = cur;
// cur = cur->next;
// }
// //删除
// pre->next = cur->next;
// printf("%d\t", cur->val);
// free(cur);
// cur = pre->next;
// }
// printf("have %d number!\n", cur->val);
//
//
//}

//辅助指针循环,用的是do-while循环,指向head停止,正好一圈
void showJoseph(Joseph_t* game) {
node_t* p = game->head;
do {
printf("%d\n", p->val);
p = p->next;
} while (p!=game->head);
printf("\n");
}`

`#pragma once
typedef int Element_t;

typedef struct _node {
Element_t val;
struct _node* next;
}node_t;

//定义Jesoph_t节点,包括头结点和尾节点,
typedef struct {
node_t* head;
node_t* tail;
}Joseph_t;

//初始化
void initJoseph(Joseph_t* game,int n);

//m表示数到几删除,m被删除后从下一个开始,直至剩下一个元素
void startJoseph(Joseph_t* game, int m);

//显示元素,用const
void showJoseph(const Joseph_t* game);
`

`#include<stdio.h>

include"joseph.h"

/**以下是几组约瑟夫环的测试答案,包括每个被杀者的顺序编号和最后的幸存者:

  • 当n=5,k=2时,被杀者的顺序编号为2, 4, 1, 5,最后的幸存者是3。
  • 当n=10,k=3时,被杀者的顺序编号为3, 6, 9, 2, 7, 1, 8, 5, 10,最后的幸存者是4。
  • 当n=7,k=2时,被杀者的顺序编号为2, 4, 6, 1, 5, 3,最后的幸存者是7。
  • 当n=10,k=17时,最后的幸存者是3。
  • */

void test01() {

Joseph_t game = { NULL,NULL };//定义节点,传空间,NULL
initJoseph(&game,10);//传指针值。地址
showJoseph(&game);
startJoseph(&game, 17);

}

int main() {
test01();
return 0;
}`

posted @ 2025-03-20 21:39  f-52Hertz  阅读(7)  评论(0)    收藏  举报