栈的链表实现细节主要在Push()和Pop()例程中链表的实现不一样。
操作图示:

Stack.c:
#ifndef STACK_H
#define STACK_H
typedef char ElementType;
struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode Stack;
int IsEmpty(Stack S);
Stack CreatStack();
void MakeEmpty(Stack S);
void DiseposeStack(Stack S);
void Push(Stack S, ElementType X);
void Pop(Stack S);
ElementType Top(Stack S);
ElementType PopAndTop(Stack S);
#endif
LinkedStack.c:
#include"Stack.h"
#include<stdio.h>
#include<stdlib.h>
struct Node{
ElementType Element;
PtrToNode Next;
};
Stack CreatStack()
{
Stack S;
S = (Stack)malloc(sizeof(struct Node));
if(S == NULL)
{
printf("sorry! malloc is failed!");
return NULL;
}
else
{
S->Next = NULL;
MakeEmpty(S);//confirm the stack is emptystack
}
return S;
}
int IsEmpty(Stack S)
{
return S->Next == NULL;
}
void MakeEmpty(Stack S)
{
if(S == NULL)
printf("Please creatstack first!");
while(!IsEmpty(S))
Pop(S);
}
void DiseposeStack(Stack S)
{
PtrToNode P, Tmp;
P = S->Next;
S->Next = NULL;
while(P != NULL)
{
Tmp = P->Next;
free(P);
P = Tmp;
}
}
void Push(Stack S, ElementType x)
{
PtrToNode NewCell;
NewCell = (Stack)malloc(sizeof(struct Node));
if(NewCell == NULL)
printf("Sorry! malloc is failed!");
else
{
NewCell->Element = x;
NewCell->Next = S->Next;
S->Next = NewCell;
}
}
void Pop(Stack S)
{
PtrToNode FirstCell;
if(IsEmpty(S))
printf("Sorry the stack is empty!");
else
{
FirstCell = S->Next;
S->Next = FirstCell->Next;
//S->Next = S->Next->Next;//这样最安全
free(FirstCell);
}
}
ElementType Top(Stack S)
{
if(!IsEmpty(S))
return S->Next->Element;
printf("Sorry! the stack is empty");
return 0;
}
ElementType PopAndTop(Stack S)
{
PtrToNode FirstCell;
ElementType FirstElement;
if(IsEmpty(S))
printf("Sorry the stack is empty!");
else
{
FirstCell = S->Next;
FirstElement = S->Next->Element;
S->Next = S->Next->Next;
free(FirstCell);
return FirstElement;
}
}