码迷,mamicode.com
首页 > 其他好文 > 详细

数据结构 堆栈

时间:2018-03-18 16:24:46      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:堆栈   creat   tac   生成   nbsp   pop   多个   print   closed   

堆栈的抽象数据类型描述

堆栈(Stack):具有一定操作约束的线性表

  • 只在一端(栈顶,Top)做插入、删除
  • 后入先出:Last In First Out(FIFO)

 

类型名称:堆栈(stack)

数据对象集:一个有0个或多个元素的又穷线性表。

操作集:长度为MaxSize的堆栈S∈Stack,堆栈元素item∈ElementType

1、Stack CreateStack(int MaxSize):生成空堆栈,其最大长度为MaxSzie;

2、int IsFull(Stack S, int MaxSize):判断堆栈S是否已满

3、void Push(Stack S, ElementType item):将元素item压入堆栈

4、int IsEmpty(Stack S):判断堆栈S是否为空

5、ElementType Pop(Stack S):删除并返回栈顶元素

 

栈的顺序存储实现

  栈的顺序存储结构通常由一个一维数组和一个记录栈顶元素位置的变量组成。

技术分享图片
#define MAXSIZE 100

typedef struct SNode *Stack;
struct SNode{
    ElementType Data[MAXSIZE];
    int Top;
}
定义

入栈

技术分享图片
void Push(Stack PtrS, ElementType item)
{
    if(PtrS->Top == MAXSIZE - 1) {
        printf("Stack full");
        return;
    } else {
        PtrS->Data[++(PtrS->Top)] = item;
        return; 
    }
}
push

出栈

技术分享图片
ElementType Pop(Stack PtrS)
{
    if(PtrS->Top == -1) {
        printf("Stack Empty");
        return ERROR;
    } else
        return(PtrS->Data[(PtrS->Top)--]);
}
pop

 

例子:请用要给数组实现两个堆栈,要求最大地利用数组空间,使数组只要有空间入栈操作就可以成功。

技术分享图片
 1 #define MAXSIZE 100
 2 struct DStack{
 3     ElementType Data[MAXSIZE];
 4     int Top1;
 5     int Top2;
 6 }S;
 7 S.Top1 = -1;
 8 S.Top2 = MAXSIZE;
 9 
10 void Push(struct DStack *PtrS, ElementType item, int Tag)
11 {
12     if(PtrS->Top2 - PtrS->Top1 == 1) {
13         printf("stack full");
14         return;
15     }
16     if(Tag == 1)
17         PtrS->Data[++(PtrS->Top1)] = item;
18     else
19         PtrS->Data[--(PtrS->Top2)] = item;
20 }
21 
22 ElementType Pop(stuct DStack *PtrS, int Tag)
23 {
24     if(Tag == 1) {
25         if(PtrS->Top == -1) {
26             ptintf("Stack1 Empty");
27             return;
28         } else {
29             return(PtrS->Data[(PtrS->Top1)--])
30         }
31    } else {
32        if(PtrS->Top2 == MAXSIZE) {
33            printf("Stack2 Empty");
34            return;
35        } else {
36            return PtrS->Data[(PtrS->Top2)--];
37        }
38    }
39 }
例子

 

数据结构 堆栈

标签:堆栈   creat   tac   生成   nbsp   pop   多个   print   closed   

原文地址:https://www.cnblogs.com/ch122633/p/8595395.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!