C语言--模拟栈(使用链表)

2019-04-14 16:53发布

使用链表模拟了栈,有压栈和弹栈
参照《程序员面试宝典》 #include <stdio.h> #include <stdlib.h> typedef struct student { int data; struct student *next; } node; typedef struct stakqueue { node *bottom,*top; }queue; // 压栈 queue *push(queue *HQ,int x) { node *s,*p; s = (node *)malloc(sizeof(node)); s->data = x; s->next = NULL; if(HQ->bottom == NULL) // 栈为空的情况 { HQ->bottom = s; HQ->top = s; } else { HQ->top->next = s; HQ->top = s; } return HQ; } //弹栈 queue *pop(queue *HQ) { node *p; int x; if(HQ->bottom == NULL) printf(" No a node! "); else { x = HQ->bottom->data; p = HQ->bottom; if(HQ->bottom == HQ->top) // 只有一个元素 { HQ->bottom = NULL; HQ->top = NULL; free(p); } else { while(p->next != HQ->top) // 因为是链表实现的栈,所以出栈得找到链表尾 p = p->next; HQ->top = p; HQ->top->next = NULL; free(p->next); } } return HQ; } //输出栈中数据 void print(queue *HQ) { node *p; p = HQ->bottom; printf("||"); while(p != NULL) { printf("%d => ",p->data); p = p->next; } printf(" "); } int main() { queue *myst = new queue(); // 压栈 for(int i = 1; i < 6; i++) { myst = push(myst,i); print(myst); } // 弹栈 for(int i = 1; i < 6; i++) { myst = pop(myst); print(myst); } getchar(); return 0; }