資料結構是以結構化方式組織的資料集合。它分為兩種類型,即線性資料結構和非線性資料結構。
線性資料結構 - 在這裡,資料以線性方式組織。
例如 - 陣列、結構體、堆疊、佇列、鍊錶。
非線性資料結構 - 在這裡,資料以層次結構方式組織。
例如 - 樹、圖、集合、表格。
它是一種線性資料結構,資料只能在一端插入和刪除。
Deleted element = 50 Item = a [top] top --
Deleted element = 40 Deleted element=30 Deleted element=20 Deleted element =10
Push ( ),Pop ( ),Display ( )的演算法
if (top = = n-1) printf("stack over flow”);
top ++ a[top] = item
if ( top = = -1) printf( "stack under flow”);
item = a[top] top --
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</p><p>”); printf ("1. push </p><p>”); printf ("2. Pop </p><p>”); printf ("3. exit </p><p>”); 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 implementation 1. Push 2. Pop 3. exit Enter ur choice : 1 [given by user] Enter an element for insertion : 10 Contents of the stack : 10 Enter ur choice : 1 Enter an element for insertion : 2 Contents of the stack : 10 20 Enter ur choice : 2 Deleted element = 20 Contents of the stack are : 10 Enter ur choice : 2 Deleted element : 10 Contents of the stack are : stack is empty Enter ur choice : 2 Stack underflow. Enter ur choice : 1 Enter an element for insertion : 30 Contents of the stack are : 30###
以上是解釋C語言中的堆疊概念的詳細內容。更多資訊請關注PHP中文網其他相關文章!