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

2024-11-29 22:06:11
推荐回答(2个)
回答1:

#include
#include

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:

这个自己写,有问题再出来问.