(数据结构初学者),问一下各位这个代码哪里有问题,自己实在是找不到了
用clion写的代码,双向链表实现的链栈,但是弹出栈顶元素永远是0。
下面是代码
```c++
#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;
}
————————————————
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/m0_68473077/article/details/140662995