/* Stacks * 15-122 Principles of Imperative Computation, Fall 2010 * Frank Pfenning */ // type elem must be defined /* Interface section for stacks */ struct stack; typedef struct stack* stack; bool is_empty(stack S); /* O(1) */ stack s_new(); /* O(1) */ void push(elem x, stack S); /* O(1) */ elem pop(stack S); /* O(1) */ struct stack { list top; }; bool is_stack (stack S) { return is_segment(S->top, NULL); } bool is_empty(stack S) //@requires is_stack(S); { return S->top == NULL; } stack s_new() //@ensures is_stack(\result); //@ensures is_empty(\result); { stack S = alloc(struct stack); S->top = NULL; return S; } void push(elem x, stack S) //@requires is_stack(S); //@ensures !is_empty(S); { list first = alloc(struct list); first->data = x; first->next = S->top; S->top = first; } elem pop(stack S) //@requires is_stack(S); //@requires !is_empty(S); //@ensures is_stack(S); { assert(S->top != NULL, "cannot pop empty stack"); { elem x = S->top->data; S->top = S->top->next; return x; } }