1.顺序栈
//
// 顺序栈的实现
//
// 包括出栈和入栈
//
//
///
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <malloc.h>
typedef char ElemType ;
#define MAXSIZE 100
#define INCREMENT 100
typedef struct SeqStack
{
int top ; // 栈顶
int base ; // 栈底
int size ; // 栈的容量
ElemType *data ; // 数据存储空间
} SeqStack ;
void InitSeqStack( SeqStack * S )
{
S->data = (ElemType*)malloc(sizeof(ElemType)*MAXSIZE) ;
if( !S->data )
{
printf("内存申请失败!\n") ;
exit(0) ;
}
S->base = 0 ;
S->top = 0 ;
S->size = MAXSIZE ;
}
bool is_full( SeqStack * S )
{
if( S->top - S->base + 1 == S->size )
{
return true ;
}
return false ;
}
bool is_empty( SeqStack * S )
{
if( S->top == S->base )
{
return true ;
}
return false ;
}
void Push( SeqStack * S , ElemType elem )
{
if( is_full( S ) ) // 栈已满
{
ElemType * base = (ElemType*)realloc( S->data , MAXSIZE + INCREMENT ) ;
if( !base )
{
printf("内存申请失败!\n") ;
exit(0) ;
}
S->data = base ;
S->size = S->top - S->base + 1 + INCREMENT ;
}
S->data[S->top++] = elem ;
}
ElemType Pop( SeqStack * S )
{
if( is_empty( S ) )
{
printf("栈为空,不能进行入栈操作!\n") ;
exit(0) ;
}
return S->data[--S->top] ;
}
void Print( SeqStack * S )
{
int i ;
for( i = S->base ; i < S->top ; i++ )
{
printf("%c ",S->data[i] ) ;
}
printf("\n" ) ;
}
int main()
{
SeqStack S ;
InitSeqStack( &S ) ;
Push( &S , 'a' ) ;
Push( &S , 'g' ) ;
Push( &S , 'h' ) ;
Push( &S , 'k' ) ;
Print( &S ) ;
Pop( &S ) ;
Pop( &S ) ;
Print( &S ) ;
return 0 ;
}
2.链栈
//
// 链栈的实现
//
// 包括出栈和入栈
//
//
///
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
#include <string.h>
typedef char ElemType ;
typedef struct Node
{
ElemType elem ;
struct Node * next ;
} Node ;
typedef struct LinkStack
{
Node * base ; // 指向栈底元素
Node * top ; // 指向栈顶元素
} LinkStack ;
void InitStack( LinkStack * L )
{
L->base = NULL ;
L->top = NULL ;
}
void Push( LinkStack * L , ElemType elem )
{
Node * tmp = (Node*)malloc(sizeof(Node)) ;
if( !tmp )
{
printf("内存申请失败!\n") ;
exit(0) ;
}
tmp->elem = elem ;
tmp->next = NULL ;
if( L->top == NULL ) // 入栈的第一个元素
{
L->base = tmp ;
L->top = tmp ;
}
else
{
L->top->next = tmp ;
L->top = tmp ;
}
}
void Pop( LinkStack * L )
{
Node *p = L->base ;
Node *q = p ;
while( p != L->top )
{
q = p ;
p = p->next ;
}
q->next = NULL ;
L->top = q ;
free( p ) ;
}
void Print( LinkStack * L )
{
Node * p = L->base ;
while( p != L->top )
{
printf("%c ", p->elem ) ;
p = p->next ;
}
if( L->base != L->top )
{
printf("%c\n" , p->elem ) ;
}
}
int main()
{
LinkStack L ;
InitStack( &L ) ;
Push( &L , 'h' ) ;
Push( &L , 'e' ) ;
Push( &L , 'l' ) ;
Push( &L , 'l' ) ;
Push( &L , 'o' ) ;
Print( &L ) ;
Pop( &L ) ;
Pop( &L ) ;
Pop( &L ) ;
Pop( &L ) ;
Pop( &L ) ;
Print( &L ) ;
return 0 ;
}