试了机组数据都对了。我忘了一部分c语言容错的语句了,没办法写得尽如人意。
#include<iostream> #include<stdlib.h> using namespace std; struct stack{ int size; int *top,*base; }; stack a; const int stacksize=10; int top() { int e; if(a.top==a.base) return -1; e=*(a.top-1); return e; } void insert(int e) { if(a.top-a.base>=a.size) { a.base=(int*)realloc(a.base,(a.size+stacksize)*sizeof(int)); a.top=a.base+a.size; a.size=a.size+stacksize; } *a.top=e; a.top=a.top+1; } void pop() { if(a.top==a.base) { cout<<"error"<<endl; return; } a.top-=1; } void clear() { while(a.top>a.base) { pop(); } } int main() { int n,i,traget,ko; a.size=stacksize; a.base=(int*)malloc(a.size*sizeof(int)); a.top=a.base; cin>>n; for(i=1;i<=n;i++) { if(a.top-a.base>=a.size) { a.base=(int*)realloc(a.base,(a.size+stacksize)*sizeof(int)); if(!a.base) exit(OVERFLOW); a.top=a.base+a.size; a.size=a.size+stacksize; } cin>>*a.top; a.top=a.top+1; } cout<<top()<<endl; cin>>ko; insert(ko); cout<<top()<<endl; pop(); cout<<top()<<endl; system("pause"); return 0; }