用clion写的代码,双向链表实现的链栈,但是弹出栈顶元素永远是0。
#include <stdio.h> #include <stdlib.h> typedef struct DSNode{ int data; struct DSNode *last; struct DSNode *next; }DSNode; typedef struct DStack{ struct DSNode *head,*tail; }DStack,* DSTack; bool InitDStack(DSTack &S) { S = (DStack*)malloc(sizeof(DStack)); DSNode *p=(DSNode*)malloc(sizeof(DSNode)); p->last=NULL; p->next=NULL; S->head=p; S->tail=p; return true; } bool StackEmpty(DSTack S) { if(S->tail==S->head) return true;//此时栈为空 else return false;//此时栈不为空 } bool push(DSTack &S,int n) { DSNode *q=(DSNode*)malloc(sizeof(DSNode)); q->data=n; q->next=NULL; q->last=S->tail; S->tail->next=q; S->tail=q; return true; } bool pop(DSTack &S,int &n) { if (StackEmpty(S)) return false; DSNode *t=S->tail; n=S->tail->data; S->tail=t->last; S->tail->next=NULL; free(t); return true; } void print(DSTack S) { while(S->tail!=S->head) { printf("%d",S->tail->data); S->tail=S->tail->last; } } int main() { DSTack S; int x; InitDStack(S); push(S,1); push(S,3); push(S,5); push(S,7); print(S); printf("\n"); pop(S,x); printf("%d",x); return 0; }