一.什么是栈
栈是限定仅在表位进行插入和删除操作的线性表 允许插入和删除的一端称为栈顶(top),另一端称为栈底(bottom),不含任何数据元素的栈称为空栈。 栈是一种先进后出的线性表(Last IN First Out),简称LIFO结构。 栈的插入操作,叫做进栈,也称压栈,入栈。 栈的删除操作,叫做出栈,也有的叫做弹栈。
二.栈的基本操作
1. InitStack ( * S) : 建立一个栈。
2. DestroyStack ( * S) :若栈存在,则销毁他。
3. ClearStack ( * S) :将栈清空。
4. StackEmpty ( S) :若栈为空,返回true,否则返回false。
5. GetTop ( * S, * e) :若栈存在且非空,用e返回S的栈顶元素。
6. Push ( * S, e) :若栈存在,插入新元素e到栈中并成为新栈顶。
7. Pop ( * S, * e) :删除栈S中的栈顶元素,并用e返回其值。
8. StackLength ( * S) :返回栈S的元素个数。
三.C语言实现栈的顺序存储结构
#include <bits/stdc++.h>
#define maxsize 100
#typedef int datatype
struct stack
{
datatype data[ maxsize] ;
struct stack * next;
} ;
typedef struct stack Stack;
Stack * s;
void init ( )
{
s= Null;
}
bool Empty ( )
{
if ( s== NULL )
return true ;
else
return false ;
}
bool full ( Stack * s)
{
if ( s- > top== maxsize- 1 )
return true ;
else
return false ;
}
void Push ( datatype element)
{
if ( ! full ( ) )
{
s. top++ ;
s. data[ s. top] = element;
}
}
void Pop ( )
{
if ( ! Empty)
s. top-- ;
else
printf ( "栈空" ) ;
}
datatype GetTop ( )
{
if ( ! Empty)
return s. data[ s. top]
else
printf ( "栈空" ) ;
}
datatype StackLength ( )
{
if ( ! Empty)
return s. top+ 1 ;
else
printf ( "栈空" ) ;
}
void Clear ( )
{
if ( ! Empty)
Pop ( ) ;
else
printf ( "栈空" ) ;
}
void Destroy ( )
{
s. top= - 1 ;
}
四.C语言实现栈的链式存储结构
#include <stdio.h>
#include <stdlib.h>
struct stack
{
int element;
struct stack * next;
} ;
struct stack* CreateStack ( void )
{
struct stack * S= malloc ( sizeof ( struct stack) ) ;
if ( S== NULL )
printf ( "error!" ) ;
else
S-> next= NULL ;
return S;
}
int Empty ( struct stack * S)
{
return S-> next== NULL ;
}
void Push ( struct stack * S, int e)
{
struct stack * p;
p= malloc ( sizeof ( struct stack) ) ;
if ( p== NULL )
printf ( "error" ) ;
else
{
p-> element= e;
p-> next= S-> next;
S-> next= p;
}
}
void Pop ( struct stack * S)
{
struct stack * p;
if ( Empty ( S) )
printf ( "error" ) ;
else
{
p= S-> next;
S-> next= p-> next;
free ( p) ;
}
}
int Top ( struct stack * S)
{
if ( Empty ( S) )
printf ( "error!" ) ;
else
return S-> next-> element;
}
void MakeEmpty ( struct stack * S)
{
if ( S== NULL )
printf ( "没有栈" ) ;
else
while ( ! Empty ( S) )
Pop ( S) ;
}
void DistoryStack ( struct stack * S)
{
MakeEmpty ( S) ;
free ( S) ;
}
int main ( )
{
struct stack * S;
S= CreateStack ( ) ;
Push ( S, 1 ) ;
Push ( S, 2 ) ;
printf ( "%d\n" , Top ( S) ) ;
return 0 ;
}