代码如下:
#include
#include
using namespace std;
#include
typedef int Status;
typedef int ElemType;
#define OK 1
#define FALSE -1
#define TURE 11
#define ERROR -1
#define INFEASIBLE -1
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
typedef struct {
ElemType elem;
int length;
int listsize;
}Sqlist;
Status InitList(Sqlist &L)
{
L.elem = (ElemType)malloc(LIST_INIT_SIZE * sizeof(ElemType));
if (!L.elem)
return 0;
L.length = 0;
L.listsize = LIST_INIT_SIZE;
return OK;
}
Status InsertElem(Sqlist &L, int i, ElemType &e) /*在第i个位置插入元素*/
{
if (iL.length+1)
return ERROR;
for (int j = L.length; j >= i; j--)
L.elem[j] = L.elem[j - 1];
L.elem[i - 1] = e;
L.length++;
return OK;
}
void KILL(Sqlist &L,int i,int j,int k)//i是总人数,j是要处决囚犯的序号,k是最后幸免的囚犯的人数
{
int n=0;
int m;
int l;
while(L.length>k)
{
l=j;
for(l;l>1;l--)
{
if(n<L.length-1)
{
n++;
}
if(n==L.length-1)
{
if(l!=1)
n=0;
if(l==1)
n=n;
}
}
cout<<L.elem[n]<<" ";
m=n;
for(m;m<L.length-1;m++) //删除第m个元素
L.elem[m]=L.elem[m+1];
L.length--;
}
cout<<endl;
}
void TraverList(Sqlist &L) /*遍历*/
{
int i;
for (i = 1; i <= L.length; i++)
cout << L.elem[i - 1]<<" " ;
cout<<endl;
}
int main()
{
int a,b,c,d;
int x;
cout<<"请输入囚犯总人数以及要处决的囚犯的序号:";
cin>>a>>b;
cout<
cout
cin>>c;
Sqlist L;
InitList(L);
cout<<"囚犯的编号是:"<
for(x=1;x
{
cin>>d;
InsertElem(L,x,d);
}
cout<<"遍历线性表:";
TraverList(L);
cout<<"被处决的囚犯依次是:"<<endl;
KILL(L,a,b,c);
cout<<"被赦免的囚犯是:";
TraverList(L);
}
结果是这样的:
请输入囚犯总人数以及要处决的囚犯的序号:6 3
请输入最后幸免的囚犯的人数:1
囚犯的编号是:
1 2 3 4 5 6
遍历线性表:1 2 3 4 5 6
被处决的囚犯依次是:
3 1 5 4 2
被赦免的囚犯是:6
而正确答案要处决囚犯的编号是3 6 4 2 5
主要问题应该是出在KILL函数,但一直找不出来,有没有大佬看一下问题出在哪?