线性表:

  顺序表:数组

  链表:链表

 

栈:也是线性表。特点是先进后出,只能从栈顶入栈和出栈。

链式栈:

  链式栈就是链表的头插法,由于是从头部插入,所以先进的后出

 

顺序栈:

//sqstack.h
#ifndef _SQ_STACK_H_
#define _SQ_STACK_H_

typedef int data_t;
typedef struct{
    data_t *data;
    int len;
    int top;
}sqstack;

sqstack *sqstack_create(int length);
int sqstack_destroy(sqstack *s);
int sqstack_push(sqstack *s, int value);
data_t sqstack_pop(sqstack *s);
int sqstack_clear(sqstack *s); 
int sqstack_empty(sqstack *s);
int sqstack_full(sqstack *s);
void sqstack_show(sqstack *s);


#endif
//sqstack.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sqstack.h"

sqstack *sqstack_create(int length)
{
    sqstack *s = (sqstack *)malloc(sizeof(sqstack));
    if(s == NULL){
        printf("malloc s failed!!\n");
        return NULL;
    }
    s->data = (data_t *)malloc(length * sizeof(data_t));
    if(s->data == NULL){
        printf("malloc s->data failed!!\n");
        free(s);
        return NULL;
    }
    s->len = length;
    s->top = -1;// -1表示一个空链表
    return s;
}

int sqstack_destroy(sqstack *s)
{
    if(s == NULL){
        printf("stack is NULL\n");
        return -1;
    }
    free(s->data);
    free(s);
}
/*
*ret @1-empty
*/
int sqstack_empty(sqstack *s)
{
    if(s == NULL){
        printf("stack is NULL\n");
        return -1;
    }
    if(s->top == -1)
        return 1;
    else 
        return 0;
}
/*
*ret @1-full
*/
int sqstack_full(sqstack *s)
{
    if(s == NULL){
        printf("stack is NULL\n");
        return -1;
    }
    if(s->top > s->len-1)
        return 1;
    else 
        return 0;
}

int sqstack_push(sqstack *s, int value)
{
    if(sqstack_full(s)){
        printf("stack is full\n");
        return -1;
    }
    s->data[++s->top] = value;
}

data_t sqstack_pop(sqstack *s)
{
    if(sqstack_empty(s)){
        printf("stack is empty\n");
        return -1;
    }
    s->top--;
    return s->data[s->top+1];
}

int sqstack_clear(sqstack *s)
{
    if(s == NULL){
        printf("stack is NULL");
        return -1;
    }
    s->top = -1;
    return 0;
}

void sqstack_show(sqstack *s)
{
    while(!sqstack_empty(s)){
        printf("%d\t",sqstack_pop(s));
    }
    printf("\n");    
}
//sqstack_test.c
#include "sqstack.h"
#include <stdio.h>

int main()
{
    int i = 0;
    sqstack *s = sqstack_create(20);
    for(i = 0; i < 20; i++){
        sqstack_push(s, i);
        printf("%d\t",i);
    }    
    printf("\n");
    sqstack_show(s);
    return 0;
}

 

posted @ 2023-04-20 16:45  踏浪而来的人  阅读(64)  评论(0编辑  收藏  举报