标签:fine 初始化 jpg abd ++ return 简单 lin ica
栈(stack)是一种被广泛使用的线性数据结构,它只允许在表的一端进行插入或删除操作,因而栈也可以被称作为操作受限的线性表 。在栈中,允许插入或删除的一端称作栈顶(top)不允许插入和删除的另一端称作栈底(bottom);
此文借助数组简单地实现栈及其基本操作。
#define MaxSize 100 typedef struct{ int data[MaxSize]; int top; }SeqStack;
注:这里假设栈中储存的是整型 (int) 的数据
void init(SeqStack* s) { s->top = -1; //数组下标从0开始,因而这里表示栈为空 }
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; }
bool isEmpty(SeqStack* s) { if(s->top==-1){ return true; }else{ return false; } }
int length(SeqStack* s) { return (s->top+1); }
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; }
#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); }
标签:fine 初始化 jpg abd ++ return 简单 lin ica
原文地址:http://www.cnblogs.com/longl/p/6414980.html