数据结构顺序栈的建立

2024-12-26 03:58:34
推荐回答(3个)
回答1:

(1) 输入形式为从键盘输入,用户根据界面的提示从键盘直接输入所对
应的数即可。输入的值为正数或字符,用户输入其他的数据会产生错误。
(2) 系统按照用户输入的数据类型,将会把相应的输出结果显示到界面
上。
(3) 测试:按照提示建立一个单链表,按照提示进行初始化、入栈、出
栈、栈的清空、栈中元素计数等操作测试程序是否正确。

回答2:

#include
#include
#define INISIZE 100
typedef struct
{
int *top;
int *base;
int size;
}sqstack;
void create(sqstack *s)
{
s->base = (int*)malloc(INISIZE*sizeof(int));
s->top = s->base;
s->size = INISIZE;
}
int main()
{
sqstack s;
create(&s);
return 0;
}

回答3:

Stack.h 1void push(int *s,int* top, int element); 2int pop(int *s,int *top); 3int full(int *top,const int size); 4int empty(int *top); 5void init(int *top); Stack.c01/* 02 initialize stack pointer 03*/04void init(int *top) 05{ 06 *top = 0; 07} 08 09/* 10 push an element into stack 11 precondition: the stack is not full 12*/13void push(int *s,int* top, int element) 14{ 15 s[(*top)++] = element; 16} 17/* 18 pop an element from stack 19 precondition: stack is not empty 20*/21int pop(int *s,int *top) 22{ 23 return s[--(*top)]; 24} 25/* 26 report stack is full nor not 27 return 1 if stack is full, otherwise return 0 28*/29int full(int *top,const int size) 30{ 31 return *top == size ? 1 : 0; 32} 33/* 34 report a stack is empty or not 35 return 1 if the stack is empty, otherwise return 0 36*/37int empty(int *top) 38{ 39 return *top == 0 ? 1 : 0; 40} teststack.c01#include 02#include 03#include "stack.h" 04 05#define size 3 06 07void main() 08{ 09 int top,element; 10 int stack[size]; 11 12 // initialize stack 13 init(&top); 14 15 // push elements into stack 16 while(!full(&top,size)){ 17 element = rand(); 18 printf("push element %d into stack\n",element); 19 push(stack,&top,element); 20 //press enter to push more 21 getchar(); 22 23 } 24 printf("stack is full\n"); 25 26 // pop elements from stack 27 while(!empty(&top)){ 28 element = pop(stack,&top); 29 printf("pop element %d from stack\n",element); 30 //press enter to pop more 31 getchar(); 32 } 33 printf("stack is empty\n"); 34 35 getchar(); 36}