josephus问题,用C语言顺序表描述,输出结果错误且出现-572662307。求大神帮忙看看代码哪里出错了!谢~
发布网友
发布时间:2023-05-01 12:28
我来回答
共2个回答
热心网友
时间:2023-10-11 22:50
#include <stdio.h>
#include <malloc.h>
#define FALSE 0
#define TRUE 1
typedef int DataType;
typedef struct SeqList {
DataType *element;
int n; // 现有元素个数
int size; // 极限表长
}*PSeqList;
PSeqList createNullList_Seq(int length) { //创建空表
PSeqList palist = (PSeqList)malloc(sizeof(struct SeqList));
if(palist) {
palist->element = (DataType *)malloc(sizeof(sizeof(DataType) * length));
if(palist->element) {
palist->n = 0;
palist->size = length;
return palist;
}
}
printf("Out of space!!\n");
return NULL;
}
int isNullList_seq(PSeqList palist) { //判别palist所指顺序表是否为空表。
return (palist->n == 0);
}
int isFullList_seq(PSeqList palist) { //判别palist所指顺序表是否为满表。
return (palist->n == palist->size);
}
int insertPre_seq(PSeqList palist, int index, DataType x) { //顺序表的插入
int i;
if(isFullList_seq(palist)) {
printf("表已满,插入操作失败!\n");
return FALSE;
}
if(index < 0 || index > palist->n) {
printf("索引错误,插入操作失败!\n");
return FALSE;
}
if(isNullList_seq(palist)) { //空顺序表插入
palist->element[0] = x; // 插入元素x
palist->n = 1; // 元素个数为1
return TRUE;
}
for(i = palist->n; i > index; i--) {
palist->element[i] = palist->element[i - 1];
}
palist->element[index] = x;
++palist->n;
return TRUE;
}
int deleteP_seq(PSeqList palist, int index) {
int i;
if(index < 0 || index > palist->n - 1){
printf("索引错误,删除操作失败!\n");
return FALSE;
}
for(i = index; i < palist->n - 1; i++){
palist->element[i] = palist->element[i + 1];
}
--palist->n;
return TRUE;
}
void josephus_seq(PSeqList palist, int m) {
int i = 0,count = 1,n = palist->n;
while(n) {
if(palist->element[i]) {
if(count == m) {
printf("Out element[%d] = %d\n", i, palist->element[i]);
palist->element[i] = 0;
--n;
count = 0;
}
++count;
}
i = (i + 1) % palist->n;
}
}
int main(){
PSeqList jos_alist;
int i, n, m;
printf("Please input the values of n = ");
scanf("%d", &n);
//scanf_s("%d", &n);
//printf("\n Please input the values of s = ");
//scanf_s("%d", &s);
printf("Please input the values of m = ");
scanf("%d", &m);
//scanf_s("%d", &m);
jos_alist = createNullList_Seq(n);
if(jos_alist) {
for(i = 0; i < n; i++){
insertPre_seq(jos_alist, i, i + 1);
}
josephus_seq(jos_alist, m);
if(jos_alist->element) free(jos_alist->element);
if(jos_alist) free(jos_alist);
}
return 0;
}
热心网友
时间:2023-10-11 22:50
这种情况极大可能是有个变量或成员变量 没有初始化导致的.