Home Java javaTutorial How many ways can a stack be implemented?

How many ways can a stack be implemented?

Jun 28, 2020 am 11:42 AM
stack Method to realize

The stack has three implementation methods. The implementation methods are: 1. Static array stack, which requires a fixed length of the structure, and the length must be determined at compile time; 2. Dynamic array stack, the length can be determined at runtime. Determine and change the length of the original array; 3. Chain structure stack, no length online, apply for allocation of memory space when needed.

How many ways can a stack be implemented?

There are 3 ways to implement the stack. The implementation methods are:

1. Static array stack

In a static array stack, STACK_SIZE represents the maximum value of the elements that the stack can store, and top_element is used as the array subscript to represent the elements in the stack. , when top_element == -1, it means the stack is empty; when top_element == STACK_SIZE - 1, it means the stack is full. When pushing, top_element increases by 1. When top_element == 0, it represents the first stack element; when popping, top_element decreases by 1.

a_stack.c source code is as follows:

[cpp] view plain copy
/* 
**  
** 静态数组实现堆栈程序 a_stack.c ,数组长度由#define确定 
*/  
  
#include"stack.h"  
#include<assert.h>  
#include<stdio.h>  
  
#define STACK_SIZE 100 /* 堆栈最大容纳元素数量 */  
  
/* 
** 存储堆栈中的数组和一个指向堆栈顶部元素的指针 
*/  
static STACK_TYPE stack[STACK_SIZE];  
static int top_element = -1;  
  
/* push */  
void push(STACK_TYPE value)  
{  
    assert(!is_full()); /* 压入堆栈之前先判断是否堆栈已满*/  
    top_element += 1;  
    stack[top_element] = value;  
}  
  
/* pop */  
void pop(void)  
{  
    assert(!is_empty()); /* 弹出堆栈之前先判断是否堆栈已空 */  
    top_element -= 1;  
}  
  
/* top */  
STACK_TYPE top(void)  
{  
    assert(!is_empty());  
    return stack[top_element];  
}  
  
/* is_empty */  
int is_empty(void)  
{  
    return top_element == -1;  
}  
  
/* is_full */  
int is_full(void)  
{  
    return top_element == STACK_SIZE - 1;  
}  
  
/* 
** 定义一个print函数,用来打印堆栈里面的元素。 
*/  
void print(void)  
{  
    int i;  
    i = top_element;  
    printf("打印出静态数组堆栈里面的值: ");  
    if(i == -1)  
        printf("这是个空堆栈\n");  
    while(i!= -1)  
        printf("%d ",stack[i--]);  
    printf("\n");  
}  
int main(void)  
{  
    print();  
    push(10); push(9); push(7); push(6); push(5);  
    push(4);  push(3); push(2); push(1); push(0);  
    printf("push压入数值后:\n");  
    print();  
    printf("\n");  
    pop();  
    pop();  
    printf("经过pop弹出几个元素后的堆栈元素:\n");  
    print();  
    printf("\n");  
    printf("top()调用出来的值: %d\n",top());  
    return 1;  
}
Copy after login

The result is as shown below:

How many ways can a stack be implemented?

## 2. Dynamic array stack

The header file still uses

stack.h. There are not many changes. The stack_size variable is added instead of STACK_SIZE to save the length of the stack. The array is replaced by a pointer, which defaults to 0 under global variables.

 

create_stackThe function first checks whether the stack has been created, then allocates the required amount of memory and checks whether the allocation is successful. destroy_stackThe function first checks whether the stack exists, and resets the length and pointer variables to zero after the memory has been released. An assertion has been added to the is_empty and is_full functions to prevent any stack function from being called before the stack is created.

d_stack.cThe source code is as follows:

[cpp] view plain copy
/* 
** 动态分配数组实现的堆栈程序 d_stack.c 
** 堆栈的长度在创建堆栈的函数被调用时候给出,该函数必须在任何其他操作堆栈的函数被调用之前条用。 
*/  
#include"stack.h"  
#include<stdio.h>  
#include<malloc.h>  
#include<assert.h>  
  
/* 
** 用于存储堆栈元素的数组和指向堆栈顶部元素的指针 
*/  
static STACK_TYPE *stack;  
static int        stack_size;  
static int        top_element = -1;  
  
/* create_stack */  
void create_stack(size_t size)  
{  
    assert(stack_size == 0);  
    stack_size = size;  
    stack = (STACK_TYPE *)malloc(stack_size * sizeof(STACK_TYPE));  
    if(stack == NULL)  
        perror("malloc分配失败");  
}  
  
/* destroy */  
void destroy_stack(void)  
{  
    assert(stack_size > 0);  
    stack_size = 0;  
    free(stack);  
    stack = NULL;  
}  
  
/* push */  
void push(STACK_TYPE value)  
{  
    assert(!is_full());  
    top_element += 1;  
    stack[top_element] = value;  
}  
  
/* pop */  
void pop(void)  
{  
    assert(!is_empty());  
    top_element -= 1;  
}  
  
/* top */  
STACK_TYPE top(void)  
{  
    assert(!is_empty());  
    return stack[top_element];  
}  
  
/* is_empty */  
int is_empty(void)  
{  
    assert(stack_size > 0);  
    return top_element == -1;  
}  
  
/* is_full */  
int is_full(void)  
{  
    assert(stack_size > 0);  
    return top_element == stack_size - 1;  
}  
  
  
/* 
** 定义一个print函数,用来打印堆栈里面的元素。 
*/  
void print(void)  
{  
    int i;  
    i = top_element;  
    printf("打印出动态数组堆栈里面的值: ");  
    if(i == -1)  
        printf("这是个空堆栈\n");  
    while(i!= -1)  
        printf("%d ",stack[i--]);  
    printf("\n");  
}  
int main(void)  
{  
    create_stack(50);  
    print();  
    push(10); push(9); push(7); push(6); push(5);  
    push(4);  push(3); push(2); push(1); push(0);  
    printf("push压入数值后:\n");  
    print();  
    printf("\n");  
    pop();  
    pop();  
    printf("经过pop弹出几个元素后的堆栈元素:\n");  
    print();  
    printf("\n");  
    printf("top()调用出来的值: %d\n",top());  
    destroy_stack();  
    return 1;  
}
Copy after login

The result is as shown below:

How many ways can a stack be implemented?

3. Chain Type stack

Since only the top element of the stack can be accessed, a linked stack can be implemented well using a singly linked list, and there is no length limit. Pushing an element onto the stack is accomplished by adding an element to the head of the linked list. Popping an element is achieved by deleting the first element at the head of the linked list. Since there is no length limit, there is no need for the

create_stack function, and destroy_stack is needed to release the memory to avoid memory leaks.

Header file

stack.h remains unchanged, l_stack.c source code is as follows:

[cpp] view plain copy
/* 
** 单链表实现堆栈,没有长度限制 
*/  
#include"stack.h"  
#include<stdio.h>  
#include<malloc.h>  
#include<assert.h>  
  
#define FALSE 0  
  
/* 
** 定义一个结构以存储堆栈元素。 
*/  
typedef struct STACK_NODE  
{  
    STACK_TYPE value;  
    struct STACK_NODE *next;  
} StackNode;  
  
/* 指向堆栈中第一个节点的指针 */  
static StackNode *stack;  
  
/* create_stack */  
void create_stack(size_t size)  
{}  
  
/* destroy_stack */  
void destroy_stack(void)  
{  
    while(!is_empty())  
        pop();  /* 逐个弹出元素,逐个释放节点内存 */  
}  
  
/* push */  
void push(STACK_TYPE value)  
{  
    StackNode *new_node;  
    new_node = (StackNode *)malloc(sizeof(StackNode));  
    if(new_node == NULL)  
        perror("malloc fail");  
    new_node->value = value;  
    new_node->next = stack;  /* 新元素插入链表头部 */  
    stack = new_node;       /* stack 重新指向链表头部 */  
}  
  
/* pop */  
void pop(void)  
{  
    StackNode *first_node;  
      
    assert(!is_empty());  
    first_node = stack;  
    stack = first_node->next;  
    free(first_node);  
}  
  
/* top */  
STACK_TYPE top(void)  
{  
    assert(!is_empty());  
    return stack->value;  
}  
  
/* is_empty */  
int is_empty(void)  
{  
    return stack == NULL;  
}  
  
/* is_full */  
int is_full(void)  
{  
    return FALSE;  
}  
  
  
/* 
** 定义一个print函数,用来打印堆栈里面的元素。 
*/  
void print(void)  
{  
    StackNode *p_node;  
    p_node = stack;  
    printf("打印出链式堆栈里面的值: ");  
    if(p_node == NULL)  
        printf("堆栈为空\n");  
    while(p_node != NULL)  
    {  
        printf("%d ", p_node->value);  
        p_node = p_node->next;  
    }  
    printf("\n");  
}  
int main(void)  
{  
    print();  
    push(10); push(9); push(7); push(6); push(5);  
    push(4);  push(3); push(2); push(1); push(0);  
    printf("push压入数值后:\n");  
    print();  
    printf("\n");  
    pop();  
    pop();  
    printf("经过pop弹出几个元素后的堆栈元素:\n");  
    print();  
    printf("\n");  
    printf("top()调用出来的值: %d\n",top());  
    destroy_stack();  
    return 1;  
}
Copy after login
The result is as shown below:

How many ways can a stack be implemented?

Recommended tutorial: "

java video tutorial"

The above is the detailed content of How many ways can a stack be implemented?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Various ways to implement batch deletion operations in MyBatis Various ways to implement batch deletion operations in MyBatis Feb 19, 2024 pm 07:31 PM

Several ways to implement batch deletion statements in MyBatis require specific code examples. In recent years, due to the increasing amount of data, batch operations have become an important part of database operations. In actual development, we often need to delete records in the database in batches. This article will focus on several ways to implement batch delete statements in MyBatis and provide corresponding code examples. Use the foreach tag to implement batch deletion. MyBatis provides the foreach tag, which can easily traverse a set.

How to customize and edit standby mode on iPhone: What's new in iOS 17 How to customize and edit standby mode on iPhone: What's new in iOS 17 Sep 21, 2023 pm 04:01 PM

Standby is a new feature in the iOS 17 update that provides a new and enhanced way to access information when your phone is idle quickly. With StandBy, you can conveniently check the time, view upcoming events, browse your calendar, get weather updates for your location, and more. Once activated, the iPhone will intuitively enter standby mode when set to landscape while charging. This feature is perfect for wireless charging points like your bedside table, or when you're away from your iPhone charging during daily tasks. It allows you to swipe through various widgets displayed in standby to access different sets of information from various applications. However, you may want to modify these widgets or even delete some based on your preferences and the information you need frequently. So let's dive into

iOS 17: How to customize widgets in standby mode iOS 17: How to customize widgets in standby mode Sep 17, 2023 pm 01:57 PM

Standby is a new customizable lock screen mode in iOS 17 that can be activated when the iPhone is charging and lying on its side. Think of it as a kind of smart display for your iPhone, allowing quick access to different browsable information screens that can be viewed from a distance while your device is charging in the kitchen, desk, or nightstand, for example. The custom standby widget consists of three screens and can be accessed by swiping horizontally on the iPhone display. The first screen is where the interactive widgets are located, while swiping to the left reveals the second and third screens, which display photos from the photo gallery and a large clock display respectively. The widget screen consists of two interactive widget stacks displayed side by side that you can swipe up and down independently. These stacks are like home screen widget stacks

OAuth2 authentication method and implementation in PHP OAuth2 authentication method and implementation in PHP Aug 07, 2023 pm 10:53 PM

OAuth2 authentication method and implementation in PHP With the development of the Internet, more and more applications need to interact with third-party platforms. In order to protect user privacy and security, many third-party platforms use the OAuth2 protocol to implement user authentication. In this article, we will introduce the OAuth2 authentication method and implementation in PHP, and attach corresponding code examples. OAuth2 is an authorization framework that allows users to authorize third-party applications to access their resources on another service provider without mentioning

The basic principles and methods of implementing inheritance methods in Golang The basic principles and methods of implementing inheritance methods in Golang Jan 20, 2024 am 09:11 AM

The basic principles and implementation methods of Golang inheritance methods In Golang, inheritance is one of the important features of object-oriented programming. Through inheritance, we can use the properties and methods of the parent class to achieve code reuse and extensibility. This article will introduce the basic principles and implementation methods of Golang inheritance methods, and provide specific code examples. The basic principle of inheritance methods In Golang, inheritance is implemented by embedding structures. When a structure is embedded in another structure, the embedded structure has embedded

What are the implementation methods of reactive programming in PHP7.0? What are the implementation methods of reactive programming in PHP7.0? May 27, 2023 am 08:24 AM

Computer programming has gone through many changes and evolutions over the past few decades. One of the latest programming paradigms is called reactive programming, which has become more popular in the development of high-quality, high-concurrency web applications. PHP is a popular web programming language that provides a rich set of libraries and frameworks to support reactive programming. In this article, we will introduce the implementation of reactive programming in PHP7.0. What is reactive programming? Before discussing PHP7.0

Three ways to implement live broadcast function in PHP Three ways to implement live broadcast function in PHP May 21, 2023 pm 11:00 PM

With the popularity of the Internet and the acceleration of high-speed networks, live broadcast has become a very popular Internet application. Live streaming can provide users with real-time video and audio streams and enable interaction and communication, so it is widely used in various social platforms and online education. In live broadcast applications, PHP is also one of the very important programming languages. Many websites and applications use PHP to implement live broadcast functions. This article will introduce three ways to implement the live broadcast function in PHP. 1. Use RTMP protocol RTMP (RealTime

A deep dive into the differences in stacks in Golang A deep dive into the differences in stacks in Golang Mar 13, 2024 pm 05:15 PM

Golang is a popular programming language with a unique design concept in concurrent programming. In Golang, the management of the stack (heap and stack) is a very important task and is crucial to understanding the operating mechanism of the Golang program. This article will delve into the differences in stacks in Golang and demonstrate the differences and connections between them through concrete code examples. In computer science, stacks are two common ways of allocating memory. They differ in memory management and data storage.

See all articles