(C语⾔)简单明了的数组模拟栈+(C++)数组模拟栈C语⾔数据结构中的很多东西都能够通过数组和链表来实现,所以熟练数组和链表是很有必要的。
栈的特点就是先进后出,如图输出。
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <memory.h>//memset库源using namespace std;
struct Stack
{
char space[1024];
int top;
};
void init(Stack *s)
{
s->top=0;
memset(s->space,0,1024);
}
bool Isfull(Stack *s)
{
return s->top==1024;
}
char pop(Stack *s)
{
return s->space[--s->top];
}
void push(Stack *s,char c)
{
s->space[s->top++]=c;
}
int Is_empty(Stack *s)
{
if(s->top==0)
return 1;
return 0;
}
int main()
{
Stack st;
init(&st);
if(!Isfull(&st))
push(&st,'a');
if(!Isfull(&st))
push(&st,'b');
if(!Isfull(&st))
push(&st,'c');
if(!Isfull(&st))
push(&st,'d');
if(!Isfull(&st))
push(&st,'e');
if(!Isfull(&st))
push(&st,'f');
while(!Is_empty(&st))
cout<<pop(&st)<<endl;
return 0;
}
如果在纯C下,把cout输出改⽤printf
#include <iostream>
#include <memory.h>
using namespace std;
struct Stack
{
void init();
bool isEmpty();
bool isFull();
char pop();
c语言listinsert函数
void push(char c);
private:
char space[1024];
int top;
};
void Stack::init()
{
top=0;
memset(space,0,1024);
}
bool Stack::isEmpty()
{
return top==0;
}
bool Stack::isFull()
{
return top==1024;
}
char Stack::pop()
{
return space[--top];
}
void Stack::push(char c)
{
space[top++]=c;
}
int main()
{
Stack st;
st.init();
for(char v='a';!st.isFull()&&v!='z'+1;++v)    {
st.push(v);
}
while(!st.isEmpty())
cout<<st.pop()<<" ";
return 0;
}
下⾯是 C++链表模拟栈/

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。