完整代码如下,其实队栈都只是链表的一种变化而已
#include#include typedef struct student * PNode;typedef struct stacklink * PStack;typedef struct student{ int data; PNode next;}Node;typedef struct stacklink{ PNode zhandi; PNode top;}Stack;PStack push(PStack stack,int num){ PNode p=(PNode)malloc(sizeof(Node)); PNode temp; PStack q=stack; p->data=num; if(stack==NULL) { q=(PStack)malloc(sizeof(Stack)); q->zhandi=p; q->top=p; q->zhandi->next=NULL; q->top->next=NULL; return q; } temp=q->top; q->top=p; q->top->next=temp; return q;}void print(PStack stack){ if(stack==NULL) { printf("栈为空\n"); return; } PStack q=stack; PNode p=q->top; while(p!=NULL) { printf("%d ",p->data); p=p->next; } printf("\n");}PStack pop(PStack stack){ if(stack==NULL) { printf("栈为空\n"); return NULL; } PStack q=stack; PNode temp=q->top; if(q->top->next==NULL) { printf("栈只有一个结点,删除完毕\n"); return NULL; } q->top=q->top->next; return q;}int main(void){ int flag; int num; PStack stack=NULL; while(1) { printf("选择入栈或者出栈:1为入栈,2为出栈,0为退出\n"); scanf("%d",&flag); if(flag==1) { printf("请选择要入栈的值:\n"); scanf("%d",&num); stack=push(stack,num); printf("打印入栈后的栈:\n"); print(stack); } else if(flag==2) { stack=pop(stack); printf("打印出栈后的队列:\n"); print(stack); } } q->top=q->top->next; return q;}int main(void){ int flag; int num; PStack stack=NULL; while(1) { printf("选择入栈或者出栈:1为入栈,2为出栈,0为退出\n"); scanf("%d",&flag); if(flag==1) { printf("请选择要入栈的值:\n"); scanf("%d",&num); stack=push(stack,num); printf("打印入栈后的栈:\n"); print(stack); } else if(flag==2) { stack=pop(stack); printf("打印出栈后的队列:\n"); print(stack); } else break; } return 0;}