数据结构之堆栈

1. 什么是堆栈

堆栈(Stack):具有一定操作约束的线性表
只在一端(栈顶,Top)做插入、删除
插入数据:入栈(Push)
删除数据:出栈(Pop)
后入先出:Last In First Out(LIFO)

2. 堆栈的抽象数据类型描述

类型名称:堆栈(Stack)
数据对象集:一个有 0 个或多个元素的有穷线性表
操作集:长度为 MaxSize 的堆栈 S ∈ Stack,堆栈元素 item ∈ ElementType
 

1. 栈的顺序存储实现

​ 栈的顺序存储结构通常由一个一维数组和一个记录栈顶元素位置的变量组成[相当于一个数组]
 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #define ElementType int
 4 #define  MAXSIZE 10
 5 typedef struct SNode* Stack;
 6 struct SNode
 7 {
 8     ElementType data[MAXSIZE];
 9     int Top;
10 };
11 //初始化
12 Stack CreateStack()
13 {
14     Stack s = (Stack)malloc(sizeof(struct SNode));
15     s->Top = -1;
16     return s;
17 }
18 //入栈
19 void Push(Stack s,ElementType item)    
20 {
21     //判断栈是否满
22     if(s->Top == MAXSIZE -1 )
23     {
24         printf("该栈已满");
25         return;
26     }
27     else
28     {
29         s->Top++;
30         s->data[s->Top] = item;
31     }
32 }
33 //出栈
34 ElementType Pop(Stack s)
35 {
36     //判断栈是否空
37     if (s->Top == -1)
38     {
39         printf("该栈已空");
40         return;
41     }
42     else
43     {
44         s->Top--;
45         return s->data[s->Top];
46     }
47 }
View Code

2. 栈的链式存储实现

​ 栈的链式存储结构实际上就是一个单链表,叫做链栈。插入和删除操作只能在链栈的栈顶进行

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #define ElementType int
 4 #define  MAXSIZE 10
 5 typedef struct SNode* Stack;
 6 struct SNode
 7 {
 8     struct SNode *next;
 9     ElementType data;
10 };
11 Stack CreateStack()
12 {
13     Stack  s = (Stack)malloc(sizeof(struct SNode));
14     s->next = NULL;
15     return s;
16 }
17 //判断堆栈是否为空
18 int IsEmpty(Stack s)
19 {
20     return (s->next == NULL);
21 }
22 //入栈【放在后面】
23 void Push(Stack s,ElementType item)
24 {
25     Stack temp = (Stack)malloc(sizeof(struct SNode));
26     temp->data = item;
27     temp->next = s->next;
28     s->next = temp;
29 }
30 //出栈【删除头结点】
31 ElementType Pop(Stack s)
32 {
33     Stack FirstCell;
34     ElementType TopElem;
35     if(IsEmpty(s))
36     {
37         printf("堆栈空");
38         return NULL;
39     }else
40     {
41         FirstCell = s->next;
42         s->next = FirstCell->next;
43         TopElem = FirstCell->data;
44         free(FirstCell);
45         return TopElem;
46     }
47 }
View Code

原文地址:https://www.cnblogs.com/Yzengxin/p/13995642.html