数据结构(二)——栈及实现、括号匹配
生活随笔
收集整理的這篇文章主要介紹了
数据结构(二)——栈及实现、括号匹配
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、棧的概念與特點
? 一種特殊的線性表,它的插入和刪除運算均在同一端進行。這一端被稱為棧頂,另一端為棧底,插入稱為進棧,刪除稱為出棧。有后進先出的性質。棧頂top相當于順序表中的size,即元素個數。關于順序表可以參考數據結構(一)——順序表及實現 。
?
?
?[注]沒有a[n]這個元素。n是元素的數量
二、棧的操作及實現
1、結構體定義
2、初始化
3、判斷是否為空
4、取得棧頂值
5、入棧操作
6、出棧操作
7、打印棧的內容
1、結構體定義
#define LENGTH 100 #include<stdio.h> #include<stdlib.h>typedef char datatype;typedef struct sequence_stack{datatype data[LENGTH];int top; }sequence_stack;2、初始化
#include"stack.h" void init_sequence_stack(sequence_stack *st){st->top = 0; }3、判斷是否為空
#include"stack.h" int is_empty_sequence_stack(sequence_stack *st){return (st->top? 0:1); }
4、取得棧頂值
5、入棧操作
6、出棧操作
7、打印棧的內容
?
三、棧的應用舉例
括號匹配:檢驗表達式中的括號是否匹配
#include<stdio.h> #include"stack.h"void compare(sequence_stack *,datatype);int main(){datatype data='\0';printf("Please input the express: ");sequence_stack Mystack;sequence_stack *stack=&Mystack;init_sequence_stack(stack);while((data=getchar()) != '\n'){switch(data){case '{':case '[':case '(':push(stack,data);break;case '}':compare(stack,'{');break;case ']':compare(stack,'[');break;case ')':compare(stack,'(');break;defult : break;}}if(is_empty_sequence_stack(stack)){printf("The bracket compare!\n");}else {printf("The bracket doesn't compare!\n");}return 0; } void compare(sequence_stack *stack,datatype data){if(get_top(stack) != data){printf("The bracket doesn't compare!\n");exit(0);}else pop(stack); }
?調試運行:
?
?本篇博客出自? 阿修羅道,轉載請注明出處:?http://blog.csdn.net/fansongy/article/details/6784919
?
?
總結
以上是生活随笔為你收集整理的数据结构(二)——栈及实现、括号匹配的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何安装iOS 13 、 macOS C
- 下一篇: 在王者荣耀角度下分析面向对象程序设计B中