利用堆栈指针PUSH和POP编写一个C语言程序

利用堆栈指针PUSH和POP编写一个C语言程序,要求20个整数区间的数列,一个函数把这20个数放进去,一个函数把这20个数释放出来。

第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);
}

}
希望能帮到你,回答有点晚,希望来得及~本回答被网友采纳
第2个回答  2010-12-06
这个自己写,有问题再出来问.
相似回答