这问题有意思,帮你写了
不过还是建议自己动手写,自己在写的过程中遇到了问题再提问,而不是直接要一个答案,直接看答案对你自己没有什么好处
stack.h#ifndef _STACK_H_
#define _STACK_H_
#include <stddef.h>
#include <stdbool.h>
typedef int element_t;
struct stack_node_tag {
element_t data;
struct stack_node_tag *next;
};
typedef struct {
struct stack_node_tag *head;
size_t size;
} stack_t;
stack_t *stack_init(void);
void stack_deinit(stack_t *s);
bool stack_push(stack_t *s, element_t e);
bool stack_pop(stack_t *s, element_t *e);
bool stack_empty(const stack_t *s);
bool stack_size(const stack_t *s, size_t *size);
bool stack_clean(stack_t *s);
#endif
stack.c#include "stack.h"
#include <stdlib.h>
stack_t *stack_init(void) {
stack_t *s = malloc(sizeof(*s));
if(!s) return NULL;
s->head = NULL;
s->size = 0;
return s;
}
void stack_deinit(stack_t *s) {
if(!s) return;
stack_clean(s); free(s);
}
bool stack_push(stack_t *s, element_t e) {
if(!s) return false;
struct stack_node_tag *node = malloc(sizeof(*node));
if(!node) return false;
node->data = e;
node->next = s->head;
s->head = node;
++s->size;
return true;
}
bool stack_pop(stack_t *s, element_t *e) {
if(!s) return false;
struct stack_node_tag *temp = s->head;
s->head = temp->next;
if(e) *e = temp->data;
free(temp); --s->size;
return true;
}
bool stack_empty(const stack_t *s) {
if(!s) abort();
return s->size == 0;
}
bool stack_size(const stack_t *s, size_t *size) {
if(!s) return false;
if(!size) return false;
*size = s->size;
return true;
}
bool stack_clean(stack_t *s) {
if(!s) return false;
while(!stack_empty(s)) stack_pop(s, NULL);
return true;
}
main.c#include "stack.h"
#include <stdio.h>
#include <string.h>
enum {ERR, PUSH, POP, END};
typedef struct {
int type;
int value;
} instruction_t;
instruction_t get_instruction(void) {
char buff[1024]; scanf("%s", buff);
instruction_t ins;
if(!strcmp(buff, "end")) {
ins.type = END;
} else if(!strcmp(buff, "push")) {
ins.type = PUSH;
scanf("%d", &ins.value);
} else if(!strcmp(buff, "pop")) {
ins.type = POP;
} else ins.type = ERR;
return ins;
}
void output(stack_t *stack) {
size_t length; stack_size(stack, &length);
printf("Stack length: %lu\n", length);
printf("stack data (from bottom to top): ");
stack_t *temp = stack_init();
while(!stack_empty(stack)) {
int data; stack_pop(stack, &data);
stack_push(temp, data);
}
while(!stack_empty(temp)) {
int data; stack_pop(temp, &data);
printf("%d ", data);
}
printf("\n");
stack_deinit(temp);
}
int main(void) {
int temp; scanf("%d", &temp); // 完全不需要这个 6
stack_t *stack = stack_init();
while(1) {
instruction_t ins = get_instruction();
if(ins.type == END) break;
switch(ins.type) {
case PUSH: stack_push(stack, ins.value); break;
case POP: stack_pop(stack, NULL); break;
}
}
output(stack);
stack_deinit(stack);
return 0;
}
|