出堆疊的問題不知道怎么改
代碼如下:
#include <stdio.h>
#include <malloc.h>
#define maxsize 100
typedef struct node{
int stack[maxsize];
int top;
}Seqstack;
Seqstack *initstack(Seqstack *s){
s=(Seqstack *)malloc(sizeof(Seqstack));
if(!s)
{ printf("空間不足\n");
return NULL; }
else { s->top=-1;
return s; }}
Seqstack *push(Seqstack *s,int x){ if(s->top==maxsize-1)
{ printf("堆疊已滿\n");
return NULL; }
else { s->top++;
s->stack[s->top]=x;
return s; }}
int pop(Seqstack *s)
{ if(s->top==-1)
{ printf("堆疊空\n");
return NULL; }
else s->top--;
return s->stack[s->top+1];}
void display(Seqstack *s)
{ if(s->top==-1)
{ printf("堆疊空\n"); }
else { while(s->top!=-1)
{ s->top--; printf("%d->",s->stack[s->top+1]); } }}
void main()
{ Seqstack *s,*p;
int i;
int a[6]={3,5,7,2,9,16};
s=initstack(s);
printf("入堆疊:");
for(i=0;i<6;i++)
s=push(s,a[i]);
display(s);
printf("\n出堆疊:");
while(s->top!=-1)
printf("%4d",pop(s));
printf("\n");}
uj5u.com熱心網友回復:
#include <stdio.h>
#include <malloc.h>
#define maxsize 100
typedef struct node {
int stack[maxsize];
int top;
}Seqstack;
Seqstack *initstack(Seqstack *s)
{
s=(Seqstack *)malloc(sizeof(Seqstack));
if(!s) {
printf("空間不足\n");
return NULL;
}
else { s->top=-1;
return s;
}
}
Seqstack *push(Seqstack *s,int x)
{
if(s->top==maxsize-1)
{
printf("堆疊已滿\n");
return NULL; }
else {
s->top++;
s->stack[s->top]=x;
return s;
}
}
int pop(Seqstack *s)
{ if(s->top==-1)
{
printf("堆疊空\n");
//return NULL; //為啥要回傳NULL?
return -1;
}
else
s->top--;
return s->stack[s->top+1];
}
void display(Seqstack *s)
{
int i = 0;
if(s->top==-1)
{
printf("堆疊空\n");
}
else {
while(i < s->top)
{
//s->top--;
printf("%d->",s->stack[i]);
i++;
}
}
}
//void main()
int main()
{ Seqstack *s,*p;
int i;
int a[6]={3,5,7,2,9,16};
s=initstack(s);
printf("入堆疊:");
for(i=0;i<6;i++)
s = push(s,a[i]);
display(s);
printf("\n出堆疊:");
while(s->top!=-1)
printf("%4d", pop(s));
printf("\n");
}
供參考~
原因是在display函式,這個函式已經修改了top值,導致在出堆疊時top已經是-1了,所以沒有出堆疊的資料了。
所以,在display函式里不要修改top的值,只是做一下遍歷即可~
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/223327.html
標籤:C語言
