Data structure series learning (6) - sequential stack (Stack)

Table of contents

introduction:

study:

Initial state:

Push state: 

Code:

Header file (SqStack.h):

Set the initial size of the sequential stack:

Set the generic type of elements in the sequential stack:

Structure design:

Declaration of all functions:

The specific implementation of the function function in the source file (SqStack):

Initialization function (Init_Stack):

Push function (Push):

Stack function (Pop):

Get the stack top element function (Top):

Empty judgment function (IsEmpty):

Judgment full function (IsFull): 

Find function (Search):

Expansion function (Inc):

Clear function (Clear):

Destroy function (Destroy):

Print function (Show):

Get effective length function (Get_Length):

test:

Test initialization function, print function:

Test the push function and expansion function:

Test the stack function:

Test clear function:

Test destroy function: 

 Test get effective length function:

Summarize:


introduction:

Data structure learning directory:

Data Structure Series Learning (1) - An Introduction to Data Structure

Data structure series learning (2) - sequence table (Contiguous_List) 

Data Structure Series Learning (3) - Singly Linked List (Linked_List) 

Data Structure Series Learning (4) - Circular Linked List 

Data Structure Series Learning (5) - Doubly Linked List (Double_Linked_List) 

In the previous article, we learned about the doubly linked list and implemented it with code. In this article, we come to understand and learn about a classic data structure——stack, and use code to implement it. It implements.

study:

In Yan Weimin's "Data Structure (C Language Edition)", the stack is defined as follows:

Stack (stack) is a linear table that is limited to insert or delete operations only at the end of the table. Therefore, for the stack, the end of the table has its special meaning, which is called the top of the stack (top), and correspondingly, the head of the table is called the bottom of the stack (bottom). An empty list with no elements is called an empty stack.

A stack is a special kind of linear table, and data can only enter from one end and exit from one end. Just like we pour water into a measuring cylinder, if we think of water as layers, then the layer of water that enters the measuring cylinder first is at the bottom of the measuring cylinder, that is, the bottom of the stack, and the layer of water that enters the measuring cylinder last Right at the head of the graduated cylinder, the top of the stack.

For example, we now have a set of data, and we need to push these five data into the stack in order from large to small :

Initial state:

Push state: 

Stack (stack) is a linear table limited to insertion and deletion operations at the end of the table.

In fact, there is nothing difficult about this thing. To put it bluntly, it is the castrated version of the sequence table.

Code:

The functions we need to implement in the sequential stack (12):

Initialization function (Init_Stack);

Push function (Push);

Stack function (Pop);

Get the value of the top element of the stack (Top);

Judgment full function (IsFull);

Empty judgment function (IsEmpty);

Find function (Search);

expansion function (Inc);

Clear function (Clear);

Destroy function (Destroy);

print function (Show);

Get the effective length function (Get_Length);

Header file (SqStack.h):

Set the initial size of the sequential stack:

#define LIST_INIT_SIZE 10//初始大小

Set the generic type of elements in the sequential stack:

typedef int ELEM_TYPE;

Structure design:

typedef struct Stack
{
    ELEM_TYPE * base;//存储空间基址(用来接收malloc返回在堆上申请的连续空间块开始地址)
    int top;//当前有效长度,且还可以表示下一个待插入位置的下标
    int listsize;//当前总空间大小
}Stack,*PStack;

Declaration of all functions:

//初始化
void Init_Stack(PStack st);
//入栈(队尾插入)
bool Push(PStack st,ELEM_TYPE val);
//出栈(队尾删除))
bool Pop(PStack st);
//获取栈顶元素值
ELEM_TYPE Top(PStack st);
//判空
bool IsEmpty(PStack st);
//判满
bool IsFull(PStack st);
//搜索
int Search(PStack st,ELEM_TYPE val);
//扩容
void Inc(PStack st);
//清空
void Clear(PStack st);
//销毁
void Destroy(PStack st);
//打印
void Show(PStack st);
//获取有效值个数
int Get_length(PStack st);

The specific implementation of the function function in the source file (SqStack):

Initialization function (Init_Stack):

We set the base in the stack to the initial size applied in the heap area and the size of the stack structure, then assign the value of top representing the number of elements in the stack to 0, and then set the initial stack size to the one we initially defined Macro replacement.

void Init_Stack(PStack st)
{
    assert(st != nullptr);
    st->base = (ELEM_TYPE*) malloc(LIST_INIT_SIZE * sizeof(Stack));
    st->top = 0;
    st->listsize = LIST_INIT_SIZE;
}

Push function (Push):

To push into the stack, the stack must first be judged to be full. If the stack is full, we will expand the capacity, and then we will assign the elements to be pushed to the top subscript position of the base group on the heap area, and then we will add 1 to the top.

bool Push(PStack st,ELEM_TYPE val)
{
    assert(st != nullptr);
    if(IsFull(st)){
        Inc(st);
    }
    st->base[st->top] = val;
    st->top++;
    return true;
}

Stack function (Pop):

When we pop the stack, the first thing to do is to judge the stack to be empty. If the stack is empty, it will return false directly. If it is not empty, we will directly reduce the number of elements in the stack by 1.

bool Pop(PStack st)
{
    assert(st != nullptr);
    if(IsEmpty(st)){
        return false;
    }
    st->top--;
    return true;
}

Get the stack top element function (Top):

Here we can directly return the element of the top-1 subscript of the base group of the generic type (similar to an array).

ELEM_TYPE Top(PStack st)
{
    assert(st != nullptr);
    return st->base[st->top-1];
}

Empty judgment function (IsEmpty):

When the number of elements in the stack is 0, the stack is empty.

bool IsEmpty(PStack st)
{
    assert(st != nullptr);
    return st->top == 0;
}

Judgment full function (IsFull): 

When the number of elements in the stack is equal to the space size of the stack, it is determined that the stack is full.

bool IsFull(PStack st)
{
    assert(st != nullptr);
    return st->top == st->listsize;
}

Find function (Search):

Similar to sequential search, define the i subscript to traverse the elements in the stack. When the value we are looking for is equal to the element corresponding to the i subscript of the base group, return the subscript of this element. If not found, then returns -1.

int Search(PStack st,ELEM_TYPE val)
{
    assert(st != nullptr);
    for(int i = 0;i < st->top;i++){
        if(val == st->base[i]){
            return i;
        }
    }
    return -1;
}

Expansion function (Inc):

Use the realloc function to double the size of the base space group originally applied for in the heap area, and then double the size of the stack space (listsize).

void Inc(PStack st)
{
    assert(st != nullptr);
    st->base = (ELEM_TYPE*) realloc(st->base,(st->listsize * sizeof(ELEM_TYPE)) * 2);
    assert(st->base != nullptr);
    st->listsize *= 2;
}

Clear function (Clear):

We directly assign the number of elements (top) in the stack to 0, thus clearing all the elements in the stack.

void Clear(PStack st)
{
    assert(st != nullptr);
    st->top = 0;
}

Destroy function (Destroy):

We directly release the space originally applied for by the malloc function on the heap area, then assign the number of elements (top) in the stack to 0, and then assign the size of the stack space (listsize) to 0.

void Destroy(PStack st)
{
    assert(st != nullptr);
    free(st->base);
    st->top = 0;
    st->listsize = 0;
}

Print function (Show):

Define a loop, the loop condition is i < top, print all the elements in the stack, and also print out the number of elements in the stack (top) and the total space of the stack (listsize).

void Show(PStack st)
{
    assert(st != nullptr);
    for(int i = 0;i < st->top;i++){
        printf("%3d",st->base[i]);
    }
    printf("\n");
    printf("栈中的元素个数top为:%d\n",st->top);
    printf("栈目前的总大小listsize为:%d\n",st->listsize);
}

Get effective length function (Get_Length):

Define the count integer value to record the number of valid values, define a loop, add 1 to the count every time the loop is executed, and set the return value of the function to count.

int Get_length(PStack st)
{
    assert(st != nullptr);
    int count = 0;
    for(int i = 0;i < st->top;i++){
        count++;
    }
    return count;
}

test:

Test initialization function, print function:

#include<cstdio>
#include<cassert>
#include<cstdlib>
#include "SqStack.h"
int main()
{
    Stack stack;
    Init_Stack(&stack);
    for(int i = 0;i < 100;i++){
        Push(&stack,i + 1);
    }
    printf("在栈上的原始数据为:\n");
    Show(&stack);
/*
    此处添加其他测试功能代码...
*/
    return 0;
}

operation result:

Test the push function and expansion function:

    Push(&stack,11);
    Show(&stack);

 operation result:

As shown in the figure, when the stack space is full, the expansion function expands the total size from the original 10 paradigms to 20, which is twice the original size.

Test the stack function:

    printf("经过出栈操作之后:\n");
    Pop(&stack);
    Show(&stack);

operation result:

Test clear function:

    printf("\n经过清空操作之后:\n");
    Clear(&stack);
    Show(&stack);

operation result:

Test destroy function: 

    printf("经过销毁操作之后:\n");
    Destroy(&stack);
    Show(&stack);

operation result:

 Test get effective length function:

Summarize:

Sequence stack is relatively simple. In fact, it is a castrated version of the sequence table. Because the principle of the data structure of the stack is first in, last out, so our stack operation is the tail insertion operation in the sequence table. Our stack The operation is the tail delete operation in the sequence table. You only need to modify the structure definition in the sequence table, and then make corresponding small changes to other functions. The overall difficulty is low.

Guess you like

Origin blog.csdn.net/weixin_45571585/article/details/127801662