Fork me on GitHub

04栈及其操作

04栈及其操作

1、栈结构体定义

typedef struct Stack
{
    int *data;
    int size, top;
} Stack;

 

2、栈初始化

Stack *init(int n)
{
    Stack *s = (Stack *)malloc(sizeof(Stack));
    s->data = (int *)malloc(sizeof(int) * n);
    s->size = n;
    s->top = -1;
    
    return s;
}

 

3、获取栈顶

int top(Stack *s)
{
    return s->data[s->top];
}

 

4、判断栈是否为空

int empty(Stack *s)
{
    return s->top == -1;
}

 

5、入栈操作

int push(Stack *s, int val)
{
    if (s == NULL) return 0;
    if (s->top == s->size - 1) return 0;
    s->data[++(s->top)] = val;
    
    return 1;
}

 

6、出栈操作

int pop(Stack *s)
{
    if (s == NULL) return 0;
    if (empty(s)) return 0;
    s->top -= 1;
    
    return 1;
}

 

7、打印/输出栈的元素

void output(Stack *s)
{
    if (s == NULL) return;
    printf("Stack : [");
    int i;
    for (i=0;i<s->top+1;i++) {
        i && printf(", ");
        printf("%d", s->data[i]);
    }
    printf("]\n");
    
    return;
}

 

8、清除栈

void clear(Stack *s)
{
    if (s == NULL) return;
    free(s->data);
    free(s);
    
    return;
}

 

9、测试及整体代码

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

typedef struct Stack
{
    int *data;
    int size, top;
} Stack;

Stack *init(int);
int top(Stack *);
int empty(Stack *);
int push(Stack *, int);
int pop(Stack *);
void output(Stack *);
void clear(Stack *);

int main()
{
    srand(time(0));
    #define max_op 20
    Stack *s = init(max_op);
    int i;
    for (i=0;i<max_op;i++) {
        int val = rand() % 100;
        int op = rand() % 4;
        switch (op) {
            case 0:
            case 1:
            case 2: {
                printf("push %d to the Stack = %d\n", val, push(s, val));
                break;
            }
            case 3: {
                printf("pop %d from the Stack = %d\n", s->data[s->top + 1], pop(s));
                break;
            }
        }
        output(s);
        printf("\n");
    }
    #undef max_op
    clear(s);
    
    return 0;
}

Stack *init(int n)
{
    Stack *s = (Stack *)malloc(sizeof(Stack));
    s->data = (int *)malloc(sizeof(int) * n);
    s->size = n;
    s->top = -1;
    
    return s;
}

int top(Stack *s)
{
    return s->data[s->top];
}

int empty(Stack *s)
{
    return s->top == -1;
}

int push(Stack *s, int val)
{
    if (s == NULL) return 0;
    if (s->top == s->size - 1) return 0;
    s->data[++(s->top)] = val;
    
    return 1;
}

int pop(Stack *s)
{
    if (s == NULL) return 0;
    if (empty(s)) return 0;
    s->top -= 1;
    
    return 1;
}

void output(Stack *s)
{
    if (s == NULL) return;
    printf("Stack : [");
    int i;
    for (i=0;i<s->top+1;i++) {
        i && printf(", ");
        printf("%d", s->data[i]);
    }
    printf("]\n");
    
    return;
}

void clear(Stack *s)
{
    if (s == NULL) return;
    free(s->data);
    free(s);
    
    return;
}

 

测试输出

 

posted @ 2020-11-08 19:56  小黑子杜  阅读(98)  评论(0编辑  收藏  举报