(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();
    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++链表模拟栈/

#include <iostream>
#include <memory.h>

using namespace std;

struct Node
{
    int data;
    struct Node * next;
};

class List
{
public:
    List *createList();
    void insertList(int d);

    void traverseList();

private:
    Node * head;
};

List * List::createList()
{
    head=new Node;
    head->next = NULL;
}

void List::insertList(int d)
{
    Node * cur = new Node;
    cur->data=d;
    cur->next = head->next;
    head->next=cur;

}

void List::traverseList()
{
    Node * ph = head->next;
    while(ph!=NULL)
    {
        cout<<ph->data<<endl;
        ph = ph->next;
    }
}

int main()
{
    List list;
    list.createList();

    for(int i=0;i<10;i++)
    {
        list.insertList(i);
    }

    list.traverseList();
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值