栈
栈(Stack):只允许在一端进行插入或删除操作的线性表。 栈顶(Top):线性表允许进行插入和删除的那一端。 栈底(Bottom):固定的,不允许进行插入和删除的另一端 特点: 1.栈是受限的线性表,所以自然具有线性关系。 2.栈中元素后进去的必然先出来,即后进先出LIFO(Last In First Out)
栈中元素后进去的必然先出来,即后进先出LIFO(Last InFirst Out) 顺序栈
栈是线性表的特例,那栈的顺序存储也是线性表顺序存储的简化。栈的顺序存储结构也叫作顺序栈。 顺序栈的操作
1.判断栈是否为空 2.判断堆栈是否已满 3.进栈 4.出栈 5.读取栈顶元素 6.删除栈顶元素 共享栈
顺序栈的存储空间大小需要事先开辟好,很多时候对每个栈各自单独开辟存储空间的利用率不如将各个栈的存储空间共享 链式栈
栈是线性表的特例,线性表的存储结构还有链式存储结构,所以也可以用链表的方式来实现栈。栈的链式存储结构也叫作链栈。 特点 1.链栈一般不存在栈满的情况。 2.空栈的判定条件通常定为top==NULL;
栈的顺序存储实现 栈的顺序存储结构通常由一个一维数组和一个记录栈顶元素位置的变量组成
#include <stdio.h>
#include <malloc.h>
#define MaxSize 100
typedef int ElementType;
typedef struct SNode * Stack;
struct SNode{
ElementType Data[ MaxSize] ;
int Top;
} ;
Stack S;
Stack CreateStack ( ) ;
int IsFull ( Stack S) ;
int IsEmpty ( Stack S) ;
void Push ( Stack S, ElementType item) ;
ElementType Pop ( Stack S) ;
Stack CreateStack ( ) {
S = ( Stack) malloc ( sizeof ( struct SNode) ) ;
S-> Top = - 1 ;
return S;
}
int IsFull ( Stack S) {
return ( S-> Top == MaxSize- 1 ) ;
}
int IsEmpty ( Stack S) {
return ( S-> Top == - 1 ) ;
}
void Push ( Stack S, ElementType item) {
if ( IsFull ( S) ) {
printf ( "堆栈满" ) ;
return ;
} else {
S-> Top++ ;
S-> Data[ S-> Top] = item;
return ;
}
}
ElementType Pop ( Stack S) {
if ( IsEmpty ( S) ) {
printf ( "堆栈空" ) ;
return ;
} else {
ElementType val = S-> Data[ S-> Top] ;
S-> Top-- ;
return val;
}
}
int main ( ) {
S = CreateStack ( ) ;
printf ( "5入栈\n" ) ;
Push ( S, 5 ) ;
printf ( "7入栈\n" ) ;
Push ( S, 7 ) ;
printf ( "66入栈\n" ) ;
Push ( S, 66 ) ;
printf ( "%d出栈\n" , Pop ( S) ) ;
printf ( "%d出栈\n" , Pop ( S) ) ;
return 0 ;
}
栈的链表存储实现 栈的链式存储结构实际上就是一个单链表,叫做链栈。插入和删除操作只能在链栈的栈顶进行
#include <stdio.h>
#include <malloc.h>
typedef int ElementType;
typedef struct SNode * Stack;
struct SNode{
ElementType Data;
Stack Next;
} ;
Stack CreateStack ( ) ;
int IsEmpty ( Stack S) ;
void Push ( Stack S, ElementType item) ;
ElementType Pop ( Stack S) ;
Stack CreateStack ( ) {
Stack S;
S = ( Stack) malloc ( sizeof ( struct SNode) ) ;
S-> Next = NULL ;
return S;
}
int IsEmpty ( Stack S) {
return ( S-> Next == NULL ) ;
}
void Push ( Stack S, ElementType item) {
Stack tmp;
tmp = ( Stack) malloc ( sizeof ( struct SNode) ) ;
tmp-> Data = item;
tmp-> Next = S-> Next;
S-> Next = tmp;
}
ElementType Pop ( Stack S) {
Stack First;
ElementType TopVal;
if ( IsEmpty ( S) ) {
printf ( "堆栈空" ) ;
return ;
} else {
First = S-> Next;
S-> Next = First-> Next;
TopVal = First-> Data;
free ( First) ;
return TopVal;
}
}
int main ( ) {
Stack S;
S = CreateStack ( ) ;
printf ( "5入栈\n" ) ;
Push ( S, 5 ) ;
printf ( "7入栈\n" ) ;
Push ( S, 7 ) ;
printf ( "66入栈\n" ) ;
Push ( S, 66 ) ;
printf ( "%d出栈\n" , Pop ( S) ) ;
printf ( "%d出栈\n" , Pop ( S) ) ;
return 0 ;
}