当前位置:网站首页>C language - stack
C language - stack
2022-07-04 10:24:00 【sqjddb】
Definition of stack
Stack (stack) Also known as the stack , It's a limitation Insert and delete only at the end of the table Operation of the The linear table
This end is called To the top of the stack , The other end is called At the bottom of the stack . The data elements in the stack comply with Last in, first out Principles .
To a stack Insert The new element is also called Into the stack 、 Push or push , Make it the new top element
From a stack Delete Elements are also called Out of stack or out of stack .
C Language implementation stack
analysis :
You can use arrays or linked lists to achieve , But the cost of inserting data into the tail of the array is relatively small . The complete procedure is as follows :
The header file
#include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>
#include<assert.h>
typedef int STDatatype;
typedef struct Stack
{
STDatatype* p;
int top;
int capacity;
}ST;
// Initialization stack
void StackInit(ST* ps);
// Free up stack space
void StackDestroy(ST* ps);
// Element stack
void StackPush(ST* ps, STDatatype x);
// Out of the stack
void StackPop(ST* ps);
// Sentenced to empty
bool StackEmpty(ST* ps);
// Calculate the number of elements in the stack
int StackSize(ST* ps);
// Back to top of stack element
STDatatype StackTop(ST* ps);
Function implementation file
#include "Stack.h"
void StackInit(ST* ps)
{
assert(ps);
ps->p = NULL;
ps->top = 0;
ps->capacity = 0;
}
void StackDestroy(ST* ps)
{
assert(ps);
if (ps->p)// If p by NULL, Can not be free
{
free(ps->p);
}
ps->p= NULL; //free After the empty , Avoid wild pointer problems
ps->top = 0;
ps->capacity = 0;
}
void StackPush(ST* ps, STDatatype x)
{
assert(ps);
// Check if there's enough space , Not enough capacity
if (ps->top == ps->capacity)
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
STDatatype* tmp = realloc(ps->p, sizeof(STDatatype)*newcapacity);
ps->p= tmp;
ps->capacity = newcapacity;
}
ps->p[ps->top] = x;
ps->top++;
}
bool StackEmpty(ST* ps)
{
assert(ps);
return ps->top == 0;
}
void StackPop(ST* ps)
{
assert(ps);
assert(!StackEmpty(ps));
ps->top--;//-> Priority over --
}
int StackSize(ST* ps)
{
assert(ps);
return ps->top;
}
STDatatype StackTop(ST* ps)
{
assert(ps);
assert(!StackEmpty(ps));
return ps->p[ps->top - 1];
}
Main function test file
#include "Stack.h"
int main()
{
ST st;
StackInit(&st);
StackPush(&st, 1);
StackPush(&st, 2);
StackPush(&st, 3);
printf("%d ", StackTop(&st));
StackPop(&st);
printf("%d ", StackTop(&st));
StackPop(&st);
StackPush(&st, 4);
StackPush(&st, 5);
while (!StackEmpty(&st))
{
printf("%d ", StackTop(&st));
StackPop(&st);
}
printf("\n");
StackDestroy(&st);
return 0;
}
Running results
Classical bracket matching problem
Ideas
Traversal string , If the current character is an open parenthesis , Push , Wait for the right parenthesis to determine whether it matches , If it's right bracket , Match the character at the top of the stack with the current character , Stack top element out of stack , Make the character at the top of the stack become an earlier left parenthesis , It is convenient to match with the more backward right parenthesis . Specific ideas and details are shown in the following program notes
#include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>
#include<assert.h>
// First, implement a stack
typedef int STDatatype;
typedef struct Stack
{
STDatatype* p;
int top;
int capacity;
}ST;
void StackPush(ST* ps, STDatatype x)
{
assert(ps);
// Check if there's enough space , Not enough capacity
if (ps->top == ps->capacity)
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
STDatatype* tmp = realloc(ps->p, sizeof(STDatatype)*newcapacity);
ps->p = tmp;
ps->capacity = newcapacity;
}
ps->p[ps->top] = x;
ps->top++;
}
void StackInit(ST* ps)
{
assert(ps);
ps->p = NULL;
ps->top = 0;
ps->capacity = 0;
}
void StackDestroy(ST* ps)
{
assert(ps);
if (ps->p)// If p by NULL, Can not be free
{
free(ps->p);
}
ps->p = NULL; //free After the empty , Avoid wild pointer problems
ps->top = 0;
ps->capacity = 0;
}
bool StackEmpty(ST* ps)
{
assert(ps);
return ps->top == 0;
}
void StackPop(ST* ps)
{
assert(ps);
assert(!StackEmpty(ps));
ps->top--;//-> Priority over --
}
STDatatype StackTop(ST* ps)
{
assert(ps);
assert(!StackEmpty(ps));
return ps->p[ps->top - 1];
}
bool isValid(char * s){
ST st;
StackInit(&st);
bool matchflag = true;
while (*s)
{
if (*s == '{' || *s == '[' || *s == '(')
{
StackPush(&st, *s);// If it's left parenthesis , Push
s++;
}
else
{
// The program comes to this , The current character is the right bracket
// If there are no elements in the stack , Indicates that there is no left parenthesis matching the current right parenthesis
if (StackEmpty(&st))
{
matchflag = false;
break;
}
// If there are elements in the stack , Take it out to match the current right parenthesis
char ch = StackTop(&st);
// The matched left parenthesis should be out of the stack
StackPop(&st);
// See if it matches
if (
(*s == '}'&&ch != '{') ||
(*s == ']'&&ch != '[') ||
(*s == ')'&&ch != '(')
)
{
matchflag = false;
break;
}
else
{
s++;// If the match , Continue traversing backwards
// See whether the following right parenthesis matches the element at the top of the stack
// It makes perfect use of the characteristics of stack first in and last out
}
}
}
if (matchflag == true)
{
matchflag = StackEmpty(&st);
// If the characters are traversed and the stack is not empty , It shows that the left parenthesis in the stack is lonely , Mismatch
}
StackDestroy(&st);
return matchflag;
}
int main()
{
// Test several examples
char *p0 = "{[]}";
printf("%d\n", isValid(p0));
char *p1= "()";
printf("%d\n", isValid(p1));
char *p2 = "()[]{}";
printf("%d\n", isValid(p2));
char *p3 = "(]";
printf("%d\n", isValid(p3));
char *p4 = "([)]";
printf("%d\n", isValid(p4));
}
Running results :
边栏推荐
- C language pointer interview question - the second bullet
- The time difference between the past time and the present time of uniapp processing, such as just, a few minutes ago, a few hours ago, a few months ago
- 2021-08-11 function pointer
- Exercise 9-3 plane vector addition (15 points)
- Normal vector point cloud rotation
- AUTOSAR从入门到精通100讲(106)-域控制器中的SOA
- Fabric of kubernetes CNI plug-in
- Some summaries of the third anniversary of joining Ping An in China
- Introduction to extensible system architecture
- Online troubleshooting
猜你喜欢
Si vous ne connaissez pas ces quatre modes de mise en cache, vous osez dire que vous connaissez la mise en cache?
Safety reinforcement learning based on linear function approximation safe RL with linear function approximation translation 1
Two way process republication + routing policy
If the uniapp is less than 1000, it will be displayed according to the original number. If the number exceeds 1000, it will be converted into 10w+ 1.3k+ display
BGP ---- border gateway routing protocol ----- basic experiment
Intelligent gateway helps improve industrial data acquisition and utilization
IPv6 comprehensive experiment
What are the advantages of automation?
leetcode842. Split the array into Fibonacci sequences
Debug:==42==ERROR: AddressSanitizer: heap-buffer-overflow on address
随机推荐
How to teach yourself to learn programming
Rhcsa - day 13
OSPF comprehensive experiment
使用 C# 提取 PDF 文件中的所有文字(支持 .NET Core)
Kotlin: collection use
Doris / Clickhouse / Hudi, a phased summary in June
Static comprehensive experiment ---hcip1
Rhsca day 11 operation
Exercise 8-10 output student grades (20 points)
Golang type comparison
Application of safety monitoring in zhizhilu Denggan reservoir area
Realsense of d435i, d435, d415, t265_ Matching and installation of viewer environment
Use the data to tell you where is the most difficult province for the college entrance examination!
Fabric of kubernetes CNI plug-in
Vs201 solution to failure to open source file HPP (or link library file)
Hands on deep learning (37) -- cyclic neural network
Exercise 7-2 finding the maximum value and its subscript (20 points)
Container cloud notes
Safety reinforcement learning based on linear function approximation safe RL with linear function approximation translation 1
Realsense d435 d435i d415 depth camera obtains RGB map, left and right infrared camera map, depth map and IMU data under ROS