//测试栈功能
#include
#include
#include "StackList.h"
int main()
{
Stack S;
initStack(S);
Push(2,S);
printf("%d",Top(S));
Push(3,S);
printf("%d",Top(S));
Pop(S);
printf("%d",Top(S));
return 0;
}
//链表栈的简单具体功能实现
#ifndef STACKLIST_H_INCLUDED
#define STACKLIST_H_INCLUDED
typedef int ElemType;
struct Node
{
ElemType element;
Node* next;
};
typedef Node *Stack;
void FatalError(char str[])
{
puts(str);
exit(0);
}
int IsEmpty(Stack S)
{
return S->next==NULL;
}
Stack initStack( Stack &S)
{
S = (Stack)malloc( sizeof(struct Node));
if( S == NULL)
{
FatalError("out of space!");
}
S->next = NULL;
return S;
}
ElemType Top(Stack S)
{
if(!IsEmpty(S))
return S->next->element;
return -1;
}
void Push(ElemType e,Stack S)
{
Stack temp;
temp = (Stack)malloc( sizeof(struct Node));
temp->element=e;
temp->next=S->next;
S->next=temp;
}
void Pop(Stack S)
{
Stack first;
first=S->next;
S->next=S->next->next;
free(first);
}
void MakeEmpty(Stack S)
{
if(S==NULL)
{
FatalError("stack is empty!!");
}
while(!IsEmpty(S))
Pop(S);
}
#endif // STACKLIST_H_INCLUDED
本文介绍了一种使用链表实现栈的数据结构方法,并通过一个简单的C语言程序演示了如何初始化栈、压栈、获取栈顶元素及弹出栈顶元素等基本操作。
792

被折叠的 条评论
为什么被折叠?



