数据结构之栈

1.4 线性结构之栈

1.4.1 栈的定义

栈(stack),是限制在只能在表的一端进行插入和删除操作的线性表。应用范围非常广泛。生活中也有栈的场景,比如堆叠的盘子、报纸,电梯中的人们,邮局的邮筒等。

特点:后进先出 (LIFO,Last In First Out)或先进后出 (FILO,First In Last Out)的线性表。
数据结构之栈_第1张图片

1.4.2 相关概念

栈顶(Top):允许进行插入、删除操作的一端,又称为表尾。栈顶由一个称为栈顶指针的位置指示器(其实就是一个变量)来指示,它是动态变化的。

栈底(Bottom):是固定不变的,不允许进行插入和删除的一端,又称为表头

空栈:不含任何元素的空表。
情况1:初始情况top = -1。
数据结构之栈_第2张图片
情况2:初始情况top = 0。
数据结构之栈_第3张图片

1.4.3 栈的存储结构

可用顺序表(数组)和链表来存储栈,栈可以依照存储结构分为两种:顺序栈和链式栈。

1.4.4 栈的功能定义

初始化栈
void initStack(Stack *stack, size_t capacity)
返回栈内元素个数
size_t getSize(const Stack *stack)
添加新元素
void push(Stack *stack, int element)
在末尾插入元素
void insertEnd(LinkedList *list, int element)
栈顶元素出栈并返回
int pop(Stack *stack)
释放栈内存
void destroyStack(Stack *stack)

1.4.5 代码实现

#include 
#include 

/***
 * 自定义顺序存储结构----》顺序栈
 */

typedef struct{
    // 存储数据指针
    int *data;
    // 指明存储容器的容量
    size_t capacity;
    size_t size;

} Stack;

// 初始化栈
void initStack(Stack *stack, size_t capacity){
    stack->data = (int *)malloc(capacity * sizeof(int));
    stack->capacity = capacity;
    stack->size = 0;
}
// 返回栈内元素个数
size_t getSize(const Stack *stack){
    return stack->size;
}

//扩容
void resizeCapacity(Stack *stack, int newCapacity){
    stack->data = (int *)realloc(stack->data, newCapacity * sizeof(int));
    stack->capacity = newCapacity;
}
// 添加新元素
void push(Stack *stack, int element){
    // 是否满了
    if (stack->size == stack->capacity){
        resizeCapacity(stack, stack->capacity + stack->capacity >> 1);
        printf("容量已满进行扩容!\n");
    }
    stack->data[stack->size] = element;
    stack->size++;
}

// 栈顶元素出栈并返回
int pop(Stack *stack){
    if (stack->size == 0){
        printf("栈空!\n");
        return -1;
    }
    int popElement = stack->data[stack->size - 1];
    stack->size--;
    return popElement;
}
// 释放栈内存
void destroyStack(Stack *stack){
    free(stack->data);
    stack->data = NULL;
    stack->capacity = 0;
    stack->size = 0;
}

//打印栈
void print(Stack *stack){
    for (int i = 0; i < stack->size; i++){
        printf("%d\t", stack->data[i]);
    }
    printf("\n");
}

int main(){
    Stack myStack;
    initStack(&myStack, 3);
    push(&myStack, 1);
    push(&myStack, 2);
    push(&myStack, 3);
    push(&myStack, 4);
    int size = getSize(&myStack);
    printf("%d\n", size);
    print(&myStack);

    getchar();
    getchar();
    return 0;
}

你可能感兴趣的:(数据结构)