比较简单,直接上代码了
#ifndef _Stack_h
struct Node;
typedef int ElementType;
typedef struct Node * PtrToNode;
typedef PtrToNode Stack;
int IsEmpty(Stack S);
Stack CreateStack(void);
void DisposeStack(Stack S);
void MakeEmpty(Stack S);
void Push(ElementType X,Stack S);
ElementType Top(Stack S);
void Pop(Stack S);
void printStack(Stack S);
#endif // _Stack_h
struct Node
{
ElementType Element;
PtrToNode Next;
};
#include <stdio.h>
#include <stdlib.h>
#include"stack.h"
int main()
{
int i=1;
int data=0;
int n;
int TopElement=0;
Stack A;
A=CreateStack();
printf("输入想要输入的节点数:");
scanf("%d",&n);
for(;i<=n;i++)
{
printf("请输入第%d个节点数为:",i);
scanf("%d",&data);
Push(data,A);
}
printStack(A);
TopElement=Top(A);
printf("栈顶元素为 %d\n",TopElement);
Pop(A);
printStack(A);
return 0;
}
int IsEmpty(Stack S)
{
return S->Next==NULL;
}
Stack CreateStack(void)
{
Stack S;
S=malloc(sizeof(struct Node));
if(S==NULL)
{
printf("Our of space");
}
S->Next=NULL;
MakeEmpty(S);
return S;
}
void MakeEmpty(Stack S)
{
if(S==NULL)
{
printf("Must use CreateStack first");
}
else
while(!IsEmpty(S))
Pop(S);
}
void Push(ElementType X,Stack S)
{
PtrToNode TmpCell;
TmpCell=malloc(sizeof(struct Node));
if(TmpCell==NULL)
{
printf("Out of space");
}
else
TmpCell ->Element=X;
TmpCell->Next=S->Next;
S->Next=TmpCell;
}
ElementType Top(Stack S)
{
if(!IsEmpty(S))
{
return S->Next->Element;
}
printf("Empty Stack");
return 0;/*Return value used to avoid warning*/
}
void Pop(Stack S)
{
PtrToNode FirstCell;
if(IsEmpty(S))
{
printf("Empty stack");
}
else
FirstCell=S->Next;
S->Next=S->Next->Next;
free(FirstCell);
}
void printStack(Stack S)
{
PtrToNode temp=S->Next;
printf("The element int the stack from top to bottom is :\n");
while(temp!=NULL)
{
printf("%d",temp->Element);
temp=temp->Next;
}
printf("\n");
运行结果:
}