栈的链式存储实际是一个单链表,叫做栈链。插入和删除应该都只在栈链的栈顶进行。
#include<stdio.h>
#include<stdlib.h>
struct Node;
typedef struct Node * PtrToNode;
typedef PtrToNode Stack;
struct Node{
ElementType element;
PtrToNode Next;
};
//创建栈
Stack createStack(){
Stack s;
s = (PtrToNode)malloc(sizeof(PtrToNode));
if(s == NULL){
printf("fail");
s->Next = NULL;
}
}
//检测栈是否为空
int isEmpty(Stack s){
return s->Next == NULL;
}
//使栈为空
void makeEmpty(Stack s){
Stack p,temp;
p = s->Next;
s->Next = NULL;
while(p!=NULL){
temp = p->Next;
free(p);
p = temp;
}
}
//入栈
void Push(ElementType ele,Stack s){
Stack tempCell;
tempCell = (PtrToNode)malloc(sizeof(PtrToNode));
if(tempCell == NULL){
tempCell->element = ele;
tempCell->Next = s->Next;
s->Next = tempCell;
}
}
//返回栈顶元素的值
ElementType Top(Stack s){
if(!isEmpty(s)){
return s->Next->element;
}else{
Error("Empty Stack\n");
return 0;
}
}
//出栈
void Pop(Stack s){
Stack firstCell;
if(!isEmpty(s)){
firstCell = s->Next;
s->Next = s->Next->Next;
free(firstCell);
}else{
Error("Empty");
}
}