栈的简单实现(1)-数组实现

引言

    栈(stack)是一种被广泛使用的线性数据结构,它只允许在表的一端进行插入或删除操作,因而栈也可以被称作为操作受限的线性表 。在栈中,允许插入或删除的一端称作栈顶(top)不允许插入和删除的另一端称作栈底(bottom);

示意图如下:

 

此文借助数组简单地实现栈及其基本操作。

代码如下:

#define MaxSize 100
typedef struct{
    int data[MaxSize];
    int top;
}SeqStack;
View Code

 

  注:这里假设栈中储存的是整型 (int) 的数据

基本操作

1.栈的初始化

void init(SeqStack* s)
{
    s->top = -1;     //数组下标从0开始,因而这里表示栈为空 
}
View Code

2.进栈

void push(SeqStack* s, int x)
{
    if(s->top<MaxSize-1)   //栈未满才能进栈 
      s->data[++(s->top)] = x;
}
View Code

3.出栈

int  pop(SeqStack* s)
{
    if(s->top>-1)   //栈不为空才能出栈 
      return (s->data[s->top--]);

}
View Code

4.清空栈

void clear(SeqStack* s)
{
    s->top = -1;
}
View Code

5.判断栈是否为空

bool isEmpty(SeqStack* s)
{
    if(s->top==-1){
        return true;
    }else{
        return false;
    }
}
View Code

6.求栈的长度

int length(SeqStack* s)
{
    return (s->top+1);
}
View Code

 

  进行测试:

int main(void)
{
    
    SeqStack s;
    init(&s);
    push(&s, 1);
    push(&s, 2);
    push(&s, 3);
    printf("%d\n", length(&s));
    
    if(isEmpty(&s)){
        printf("栈为空\n");
    }else{
        printf("栈不为空\n");
    }
    
    printf("%d\n", pop(&s));
    printf("%d\n", pop(&s));    
    printf("%d\n", pop(&s));
    
    if(isEmpty(&s)){
        printf("栈为空\n");
    }else{
        printf("栈不为空\n");
    }
    
    push(&s, 3);
    clear(&s);
    if(isEmpty(&s)){
        printf("栈为空\n");
    }else{
        printf("栈不为空\n");
    }    
    
    return 0;
}
View Code

  测试结果:

完整代码

#include<stdio.h>
#define MaxSize 100
typedef struct{
    int data[MaxSize];
    int top;
}SeqStack;

void init(SeqStack* s);
bool isEmpty(SeqStack* s);
void push(SeqStack* s, int x);
int  pop(SeqStack* s);
void clear(SeqStack* s);
int length(SeqStack* s);


int main(void)
{
    
    SeqStack s;
    init(&s);
    push(&s, 1);
    push(&s, 2);
    push(&s, 3);
    printf("%d\n", length(&s));
    
    if(isEmpty(&s)){
        printf("栈为空\n");
    }else{
        printf("栈不为空\n");
    }
    
    printf("%d\n", pop(&s));
    printf("%d\n", pop(&s));    
    printf("%d\n", pop(&s));
    
    if(isEmpty(&s)){
        printf("栈为空\n");
    }else{
        printf("栈不为空\n");
    }
    
    push(&s, 3);
    clear(&s);
    if(isEmpty(&s)){
        printf("栈为空\n");
    }else{
        printf("栈不为空\n");
    }    
    
    return 0;
}


void init(SeqStack* s)
{
    s->top = -1;     //数组下标从0开始,因而这里表示栈为空 
}

bool isEmpty(SeqStack* s)
{
    if(s->top==-1){
        return true;
    }else{
        return false;
    }
}

void push(SeqStack* s, int x)
{
    if(s->top<MaxSize-1)   //栈未满才能进栈 
      s->data[++(s->top)] = x;
}

int  pop(SeqStack* s)
{
    if(s->top>-1)   //栈不为空才能出栈 
      return (s->data[s->top--]);   

}

void clear(SeqStack* s)
{
    s->top = -1;
}

int length(SeqStack* s)
{
    return (s->top+1);
}
View Code

 

 

 

 

 

posted @ 2017-02-19 10:55  BrysonChen  阅读(553)  评论(0编辑  收藏  举报