|
楼主 |
发表于 2019-4-22 09:07:00
|
显示全部楼层
目前能够做到的就是这样……输入3和4都可以得到正确结果……
但当我输入5,的时候,本应该是没有结果,但是却告诉我程序运行出错……
应该有可能是内存溢出了?求大家帮忙看一下到底是怎么回事?
- #include <stdio.h>
- #include <stdlib.h>
- #define Max 100
- int array[Max*2]={0};
- int visit[Max][Max*2]={0};
- typedef struct
- {
- int no[Max];
- int posi[Max*2];
- int top;
- }Stack;
- void Inite(Stack *&s,int n)
- {
- int i;
- s=(Stack *)malloc(sizeof(Stack));
- s->top=-1;
- for(i=n*2;i<Max*2;i++)
- array[i]=-1;
- }
- void Destroy(Stack *&s)
- {
- free(s);
- }
- void Push(Stack *&s,int i,int p) //入栈,填数字,将visit[p]记为1
- {
- //入栈常规操作
- s->top++;
- s->no[s->top]=i;
- s->posi[s->top]=p;
- //将数字放进数组里
- array[p]=array[p+i+1]=i;
- //这个位置i试过了
- visit[i-1][p]=1;
- }
- void Pop(Stack *&s,int n) //出栈,数组恢复,重置visit
- {
- int i,p;
- int j,k;
- //出栈常规操作
- i=s->no[s->top];
- p=s->posi[s->top];
- s->top--;
- //将数字从数组里取出
- array[p]=array[p+i+1]=0;
- //将出栈元素之前的所有元素的visit重置
- for(k=0;k<i-1;k++)
- for(j=0;j<n*2;j++)
- visit[i-2][j]=0;
- }
- bool Empty(Stack *&s)
- {
- return s->top==-1;
- }
- void PopAll(Stack *&s,int n)
- {
- while(!Empty(s))
- Pop(s,n);
- }
- void Disp(int n)
- {
- int i;
- int p,q;
- for(i=0;i<2*n;i++)
- {
- printf("%d ",array[i]);
- }
- printf("\n");
- for(p=0;p<n-1;p++)
- for(q=0;q<2*n;q++)
- visit[p][q]=0;
- for(p=0;p<2*n;p++)
- array[p]=0;
- }
- void sort(Stack *&s,int n)
- {
- int i=n,p,j;
- int count=0;
- while(1)
- {
- for(i;i>0;i--) //i用于计数
- {
- for(p=0;p<2*n-i-1;p++) //p用来定位
- {
- if(array[p]==0 && array[p+i+1]==0 && visit[i-1][p]==0)//这个位置和间隔i个位置都有空而且这个位置以前没放过
- {
- Push(s,i,p); //入栈,填数字,将visit[p]记为1
- break;
- }
- }
- if(p==2*n-i-1) //所有位置都试过一遍了
- {
- Pop(s,n); //出栈,数组恢复,重置visit
- i+=2; //重新排出栈的那个元素
- }
- }
- //判断是否要打印
- for(j=0;j<n*2;j++)
- if(array[j]==0)
- goto next;
- Disp(n);
- i=n;
- PopAll(s,n);
- count++;
- //判断是否全都循环过一遍
- next: for(j=0;j<n-1;j++)
- if(visit[n-1][j]==0)
- goto end;
- break;
- end: ;
- }
- if(count==0)
- printf("无\n");
- }
- int main()
- {
- int n;
- Stack *s;
- printf("Input a number:( must more than 0 and less than 101 )\n");
- scanf("%d",&n);
- Inite(s,n);
- sort(s,n);
- Destroy(s);
- return 0;
- }
复制代码 |
|