第1个回答 推荐于2018-04-21
#include <stdio.h>
#include <stdlib.h>
struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode Stack;
struct Node
{
int x;
PtrToNode Next;
};
int IsEmpty( Stack s )
{
return s->Next == NULL;
}
void Push( int x, Stack s )//压栈
{
PtrToNode TmpCell;
TmpCell = malloc( sizeof( struct Node ) );
if( TmpCell == NULL)
{
printf("Out of Space!!");
exit(0);
}
else
{
TmpCell->x = x;
TmpCell->Next = s->Next;
s->Next = TmpCell;
printf("%d has been pushed!\n",x);
}
}
int Top( Stack s )//返回栈顶元素
{
if( !IsEmpty( s ))
{
return s->x;
}
printf("The stack is Empty!");
return -1;
}
void Pop( Stack s )//出栈
{
PtrToNode FirstCell;
if( IsEmpty( s ) )
{
printf("The stack is Empty!");
return;
}
else
{
FirstCell = s->Next;
s->Next = s->Next->Next;
printf("%d has been poped!\n",FirstCell->x);
free(FirstCell);
}
}
void MakeEmpty( Stack s )//清空栈
{
if( s == NULL )
{
printf( "Must use CreateStack first" );
return;
}
else
{
while( !IsEmpty( s ) )
{
Pop(s);
}
}
}
Stack CreateStack()//创建新栈
{
Stack s = malloc( sizeof( struct Node ) );
if( s == NULL )
{
printf( "Out of space!" );
exit(0);
}
s->Next = NULL;
MakeEmpty( s );
return s;
}
void main()
{
int i;
Stack s;
s = CreateStack();
for(i=1;i<=20;++i)//将1~20压入栈
{
Push(i,s);
}
for(i=1;i<=20;++i)
{
Pop(s);
}
}
希望能帮到你,回答有点晚,希望来得及~本回答被网友采纳