1. 程式人生 > 其它 >棧的基本操作(順序棧)

棧的基本操作(順序棧)

棧的基本操作有棧的初始化、插入資料、刪除資料以及遍歷棧。

棧的特點是先進後出,因此先插入的資料在遍歷的時候最後被輸出。刪除資料的時候,先刪除後插入的資料。

如下圖所示:

結構體定義程式碼:(這是其中一種定義結構體的方法)

typedef struct Stack{
    int *top;
    int *bottom;
    int Stack_size;
}Stack;

相應的操作對應的程式碼為:

//初始棧

int InitStack(Stack *stack){
    stack->bottom=(int *)malloc(SIZE*sizeof(int));
    stack
->top=stack->bottom; stack->Stack_size=SIZE; return OK; }

//插入資料

int Push(Stack *stack,int data){
    if(stack->top-stack->bottom>=stack->Stack_size){
        printf("棧已滿,不能插入資料");
    }
    *stack->top=data;
    stack->top++;
    return OK;
}

//刪除資料

int Pop(Stack *stack){
    
if(stack->bottom==stack->top){ printf("棧為空,不能刪除資料"); } stack->top--; printf("%d\n",*stack->top); return OK; }

//遍歷棧

int print(Stack *stack)
{
    while(stack->bottom!=stack->top){
            stack->top--;
        printf("%d",*stack->top);
    }
    return
OK; }

完整程式碼為:

 1 #define OK 1
 2 #define ERROR 0
 3 #define SIZE 100
 4 typedef struct Stack{
 5     int *top;
 6     int *bottom;
 7     int Stack_size;
 8 }Stack;
 9 //初始棧
10 int InitStack(Stack *stack){
11     stack->bottom=(int *)malloc(SIZE*sizeof(int));
12     stack->top=stack->bottom;
13     stack->Stack_size=SIZE;
14     return OK;
15 }
16 //插入資料
17 int Push(Stack *stack,int data){
18     if(stack->top-stack->bottom>=stack->Stack_size){
19         printf("棧已滿,不能插入資料");
20     }
21     *stack->top=data;
22     stack->top++;
23     return OK;
24 }
25 //刪除資料
26 int Pop(Stack *stack){
27     if(stack->bottom==stack->top){
28         printf("棧為空,不能刪除資料");
29     }
30     stack->top--;
31     printf("%d\n",*stack->top);
32     return OK;
33 }
34 //遍歷棧
35 int print(Stack *stack)
36 {
37     while(stack->bottom!=stack->top){
38             stack->top--;
39         printf("%d",*stack->top);
40     }
41     return OK;
42 }
43 int main()
44 {
45     Stack a;
46     InitStack(&a);
47     Push(&a,1);
48     Push(&a,2);
49     Push(&a,3);
50     printf("刪除的元素是:");
51     Pop(&a);
52     printf("剩餘的元素是:");
53     print(&a);
54     return 0;
55 }

執行結果如圖所示: