还是老问题想清楚栈顶是在链表头还是链表尾呢,当然链表头啊!
#include <stdio.h>
#include <stdlib.h>
typedef struct SNode *Stack;
struct SNode{
int data;
Stack next;
};
Stack CreateStack(){
Stack s;
s = (Stack) malloc (sizeof(struct SNode));
s->next = NULL;
return s;
}
void Push(Stack Ptrs, int x) {
Stack s;
s = (Stack)malloc(sizeof(struct SNode));
s->data = x;
s->next = Ptrs->next;
Ptrs->next = s;
}
int Pop(Stack Ptrs) {
Stack s;
int item;
if(Ptrs->next == NULL) {
printf("栈空");
return -1;
}
else
{
s = Ptrs->next;
Ptrs->next = s->next;
item = s->data;
free(s);
return item;
}
}
int main() {
Stack s;
s = CreateStack();
for(int i = 0; i <5; i++)
Push(s,i+1);
for(int i = 0; i <5; i++)
printf("%d ", Pop(s));
return 0;
}