// ListStack.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
//链式栈的实现
//链式栈栈顶指针在头节点,压栈都是压首元节点,相当与链表头插法,出栈也是出首元节点
typedef int SElemType;
typedef struct node{
SElemType data;
struct node * link;
}LinkNode,*LinkStack;
//栈示意图:
//LinNode -> An->An-1->An-2 .......->A1
//初始化栈
bool Init( LinkStack &s )
{
s = new LinkNode();
if( s == NULL ) return false;
s->link = NULL;
}
//是否是空栈
bool IsEmpty( LinkStack &s )
{
return (s->link == NULL)?true:false;
}
//压栈,其实就是链表头插法
bool Push( LinkStack &s, SElemType x )
{
LinkStack p = new LinkNode();
if( p == NULL ) return false;
p->data = x;
p->link = s->link;
s->link = p;
return true;
}
//出栈,出的是头节点后面的一个节点,即首节点
bool Pop( LinkStack &s, SElemType &x )
{
if(IsEmpty(s)) return false;
LinkNode *p = s->link;
s->link = p->link;
x = p->data;
delete p;
return true;
}
//得到栈顶元素
bool GetTop( LinkStack &s ,SElemType &x )
{
if(IsEmpty(s)) return false;
x = s->link->data;
return true;
}
//栈长度
int GetStackSize( LinkStack &s )
{
if(IsEmpty(s))return 0;
LinkStack p = s->link;
int i = 0;
while(p != NULL )
{
p = p->link;
i++;
}
return i;
}
//清空栈
void ClearStack( LinkStack &s )
{
LinkStack p;
while( s->link != NULL )
{
p = s->link;
s->link = p->link;
delete p;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
LinkStack s;
Init(s);
int i = 1;
for(; i<30; i++)
{
Push(s,i);
}
printf("入栈后栈大小=%d\n",GetStackSize(s));
SElemType x;
for(i--; i!=0; i--)
{
Pop(s,x);
printf("出栈第%d元素=%d\n",i,x);
}
printf("出栈后栈大小=%d\n",GetStackSize(s));
ClearStack(s);
delete s;
getchar();
return 0;
}
c链式栈的实现
最新推荐文章于 2023-04-14 09:35:40 发布