补全代码#include<stdio.h> #include<stdlib.h> typedef struct Stack{ int *data; int size, top; }Stack; Stack *init_stack(int n) { Stack *s = (Stack *)malloc(sizeof(Stack)); s->data = (int *)malloc(sizeof(int)); s->top = -1; s->size = n; return s; } void clear(Stack *s) { free(s->data); free(s); } int main() { return 0; }
时间: 2024-01-29 18:03:22 浏览: 63
c代码-栈(顺序存储)
这是一个基本的栈结构的定义和初始化函数以及清空函数的代码,但是缺少了栈的一些操作函数,比如 push()、pop()、peek() 等。可以参考下面的代码进行补充:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct Stack{
int *data;
int size, top;
}Stack;
Stack *init_stack(int n) {
Stack *s = (Stack *)malloc(sizeof(Stack));
s->data = (int *)malloc(sizeof(int) * n);
s->top = -1;
s->size = n;
return s;
}
void clear(Stack *s) {
free(s->data);
free(s);
}
int push(Stack *s, int x) {
if (s->top == s->size - 1) {
return 0; // 栈满了
}
s->top++;
s->data[s->top] = x;
return 1;
}
int pop(Stack *s) {
if (s->top == -1) {
return 0; // 栈空了
}
s->top--;
return 1;
}
int peek(Stack *s) {
if (s->top == -1) {
return -1; // 栈空了
}
return s->data[s->top];
}
int main() {
Stack *s = init_stack(10);
push(s, 1);
push(s, 2);
push(s, 3);
printf("%d\n", peek(s)); // 输出3
pop(s);
printf("%d\n", peek(s)); // 输出2
clear(s);
return 0;
}
```
阅读全文