用数据结构c++顺序表和链表实现约瑟夫环问题,输出每次出列的编号和幸存者的编号。
时间: 2024-05-12 15:19:55 浏览: 69
C++ 中循环链表和约瑟夫环
顺序表实现:
```c
#include <stdio.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int length;
} SqList;
int josephus(SqList *list, int k) {
int i, index = 0;
while (list->length > 1) {
index = (index + k - 1) % list->length;
printf("%d 出列\n", list->data[index]);
for (i = index; i < list->length - 1; i++) {
list->data[i] = list->data[i + 1];
}
list->length--;
}
return list->data[0];
}
int main() {
SqList list = {{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 10};
int k = 3;
int survivor = josephus(&list, k);
printf("幸存者编号:%d\n", survivor);
return 0;
}
```
链表实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} ListNode;
ListNode *createList(int n) {
int i;
ListNode *head, *p;
head = (ListNode *) malloc(sizeof(ListNode));
head->next = NULL;
p = head;
for (i = 1; i <= n; i++) {
ListNode *node = (ListNode *) malloc(sizeof(ListNode));
node->data = i;
node->next = NULL;
p->next = node;
p = node;
}
p->next = head->next;
return head;
}
int josephus(ListNode *head, int k) {
int i, index = 0;
ListNode *p = head, *q;
while (p->next != p) {
for (i = 1; i < k; i++) {
q = p;
p = p->next;
}
index = p->data;
printf("%d 出列\n", index);
q->next = p->next;
free(p);
p = q->next;
}
return p->data;
}
int main() {
int n = 10, k = 3;
ListNode *head = createList(n);
int survivor = josephus(head, k);
printf("幸存者编号:%d\n", survivor);
return 0;
}
```
阅读全文