世界之光2007 世界之光2007
C
关注数: 15 粉丝数: 22 发帖数: 1,161 关注贴吧数: 35
我这个是栈吗? #include "stdio.h" #include "stdlib.h" #include "stdbool.h" #define STACKCOUNT 10 typedef int Item; typedef struct node{ Item item; struct node *prev; }Node; typedef struct stack{ size_t size; Node *top; }Stack; static void CopytoNode(Item item, Node* pn) { pn->item = item; } static void CopytoItem(Node* pn, Item *pi) { *pi = pn->item; } void InitStack(Stack *ps) { ps->size = 0; ps->top = NULL; } int StackIsEmpty(const Stack* ps) { return ps->size == 0 ? 1 : 0; } int StackIsFull(const Stack* ps) { return ps->size == STACKCOUNT ? 1 : 0; } size_t StackSize(const Stack *ps) { return ps->size; } int PushStack(Item item, Stack *ps) { if(StackIsFull(ps)) return 0; Node* pn = (Node*)malloc(sizeof(Node)); CopytoNode(item, pn); pn->prev = ps->top; ps->top = pn; ps->size += 1; return 1; } int PopStack(Stack* ps, Item *pi) { if(StackIsEmpty(ps)) return 0; Node* pt = ps->top; CopytoItem(pt, pi); ps->top = ps->top->prev; ps->size -= 1; free(pt); return 1; } void EmptyStack(Stack* ps) { Item item; while(!StackIsEmpty(ps)) PopStack(ps, &item); } int main() { Stack cup; Item num; char c; InitStack(&cup); printf("Enter 'a' to add, 'd' to del, " "or 'q' to quit:"); while((c = getchar()) != 'q') { if(c!='a' && c!='d') continue; if(c == 'a') { printf("Input a num to PushStack: "); scanf("%d", &num); if(!StackIsFull(&cup)) { PushStack(num, &cup); printf("%d has been pushed to stack.\n", num); printf("the stack has %d items now.\n", cup.size); } else printf("Failed, the stack is full!\n"); } else { if(!StackIsEmpty(&cup)) { PopStack(&cup, &num); printf("%d has been popped, and %d ite***eft.\n", num, cup.size); } else printf("Failed. The stack is empty.\n"); } printf("Enter 'a' 'd' or 'q' to quit:"); } EmptyStack(&cup); return 0;
1 下一页