数据结构是以结构化方式组织的数据集合。它分为两种类型,即线性数据结构和非线性数据结构。
线性数据结构 - 在这里,数据以线性方式组织。
例如 - 数组、结构体、栈、队列、链表。
非线性数据结构 - 在这里,数据以层次结构方式组织。
例如 - 树、图、集合、表格。
c语言中的栈它是一种线性数据结构,数据只能在一端插入和删除。
操作push - 将元素插入栈中。pop - 从栈中删除元素。
deleted element = 50item = a [top]top --
pop() ,pop(),pop(), pop()deleted element = 40deleted element=30deleted element=20deleted element =10
pop ( )堆栈溢出
条件堆栈溢出 - 尝试向满栈插入元素。
堆栈下溢 - 尝试从空栈中删除元素。
push ( ),pop ( ),display ( )的算法相应的算法如下:
push ( )检查堆栈是否溢出。if (top = = n-1)printf("stack over flow”);
否则,将一个元素插入到堆栈中。top ++a[top] = item
pop ( )检查堆栈下溢。if ( top = = -1)printf( "stack under flow”);
否则,从堆栈中删除该元素。item = a[top]top --
display ( )检查堆栈流程。if (top == -1)printf ("stack is empty”);
否则,按照下面提到的算法进行操作 −for (i=0; i<top; i++)printf ("%d”, a[i]);
示例以下是使用数组实现堆栈的c程序:
#include<stdio.h>#include <conio.h>int top = -1, n,a[100];main ( ){ int ch; void pop ( ); void display ( ); clrscr ( ); printf ("enter the size of the stack”); scanf ("%d”, &n); printf("stack implementation
”); printf ("1. push
”); printf ("2. pop
”); printf ("3. exit
”); do{ printf ( "enter ur choice”); scanf ("%d”, &ch); switch (ch){ case 1 : push ( ); display ( ); break; case 2 : push ( ); display ( ); break; case 3 : exit } }while (ch>=1 | | ch<= 3); getch ( );}void push ( ){ int item; if (top = = n-1) printf ( "stack over flow”) else{ printf("enter an element for insertion”) scanf ("%d”, &item); top ++; a[top] = item; }}void pop ( ){ int item; if (top = = -1); printf ( "stack under flow”); else{ item = a[top]; top --; printf("deleted element = %d”, item); }}void display ( ){ int i; if (top = = -1) printf ( "stack is empty”); else{ printf("contents of the stack are”); for (i=0; i<top; i++) printf ("%d \t”, a[i]); }}
输出当执行上述程序时,它会产生以下结果 −
enter the size of the stack = 5 [given by user]stack implementation1. push 2. pop 3. exitenter ur choice : 1 [given by user]enter an element for insertion : 10contents of the stack : 10enter ur choice : 1enter an element for insertion : 2contents of the stack : 10 20enter ur choice : 2deleted element = 20contents of the stack are : 10enter ur choice : 2deleted element : 10contents of the stack are : stack is emptyenter ur choice : 2stack underflow.enter ur choice : 1enter an element for insertion : 30contents of the stack are : 30
以上就是解释c语言中的堆栈概念的详细内容。
