如题;这是一套完整的可运行的代码;需要读者有一定的基础去阅读;
语言是用C语言实现;在C++环境中编写;在C++中可直接运行;在C语言中需要改部分头文件和输出语句;
头文件;这要是代码的声明部分;
# ifndef _HEAD_
# define _HEAD_
# include <iostream>
using namespace std;
typedef int DataType;
typedef struct Node
{
DataType data;
struct Node * next;
}SNode, * PSNode;
typedef struct
{
PSNode top;
}LinkStack, * PLinkStack;
PLinkStack CreateLinkStack(void);
void DestroyLinkStack(PLinkStack * pS);
bool EmptyLinkStack(PLinkStack S);
bool PushLinkStack(PLinkStack S, DataType x);
bool PopLinkStack(PLinkStack S, DataType * val);
bool GetTopLinkStack(PLinkStack S, DataType * val);
# endif
实现文件;主要是代码的实现;
# include "Head.h"
PLinkStack CreateLinkStack(void)
{
PLinkStack S = (PLinkStack)malloc(sizeof(LinkStack));
if (NULL != S)
{
S->top = NULL;
return S;
}
else
{
cout << "Memory allocate is error! " << endl;
system("pause");
exit(0);
}
}
void DestroyLinkStack(PLinkStack * pS)
{
PLinkStack S = *pS;
PSNode p = S->top;
PSNode q = NULL;
while (NULL != p)
{
q = p;
p = p->next;
free(q);
q = NULL;
}
free(S);
S = NULL;
*pS = NULL;
return;
}
bool EmptyLinkStack(PLinkStack S)
{
if (NULL == S->top)
{
return true;
}
else
{
return false;
}
}
bool PushLinkStack(PLinkStack S, DataType x)
{
PSNode p = (PSNode)malloc(sizeof(SNode));
if (NULL == p)
{
return false;
}
else
{
p->data = x;
p->next = NULL;
p->next = S->top;
S->top = p;
return true;
}
}
bool PopLinkStack(PLinkStack S, DataType * val)
{
if (EmptyLinkStack(S))
{
return false;
}
else
{
PSNode p = S->top;
S->top = p->next;
*val = p->data;
free(p);
p = NULL;
}
}
bool GetTopLinkStack(PLinkStack S, DataType * val)
{
if (EmptyLinkStack(S))
{
return false;
}
else
{
*val = S->top->data;
return true;
}
}
Main函数;
# include "Head.h"
int main(int argc, char ** argv)
{
int val = 0;
PLinkStack s = CreateLinkStack();
for (int i = 0; i < 10; i++)
{
PushLinkStack(s, i + 1);
}
for (int i = 0; i < 10; i++)
{
PopLinkStack(s, &val);
cout << val << " ";
}
cout << endl;
cout << EmptyLinkStack(s) << endl;
DestroyLinkStack(&s);
if (NULL == s)
{
cout << "test" << endl;
}
system("pause");
return 0;
}