【C++语法实践】03-C和C++实现栈

C语言版本

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

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

struct Stack
{
    struct Link* head;
    int size;
};

void InitStack(struct Stack* stack)
{
    stack->head = NULL;
    stack->size = 0;
}

void StackPush(struct Stack* stack, const int data)
{
    struct Link* node;
    node = (struct Link*)malloc(sizeof(struct Link));
    assert(node != NULL);
    node->data = data;
    node->next = stack->head;
    stack->head = node;
    ++stack->size;
}

int StackEmpty(struct Stack* stack)
{
    return (stack->size == 0);
}

int StackPop(struct Stack* stack, int* data)
{
    if (StackEmpty(stack))
        return 0;

    struct Link* tmp = stack->head;
    *data = stack->head->data;
    stack->head = stack->head->next;
    --stack->size;
    free(tmp);
    return 1;
}

void StackCleanup(struct Stack* stack)
{
    struct Link* tmp;
    while (stack->head)
    {
        tmp = stack->head;
        stack->head = stack->head->next;
        free(tmp);
    }

    stack->size = 0;
}

int main()
{
    struct Stack stack;
    InitStack(&stack);
    int i;

    for (i = 0; i < 5; i++)
    {
        StackPush(&stack, i);
    }

    while (!StackEmpty(&stack))
    {
        StackPop(&stack, &i);
        printf("%d ", i);
    }
    printf("\n");
    return 0;
}

C++版本

#include <iostream>
using namespace std;

class Stack
{
    struct Link
    {
        int data_;
        Link* next_;
        Link(int data, Link* next) : data_(data), next_(next)
        {

        }
    };

public:
    Stack() : size_(0), head_(0)
    {

    }

    ~Stack()
    {
        Link* tmp;
        while (this->head_)
        {
            tmp = this->head_;
            this->head_ = this->head_->next_;
            delete tmp;
        }
    }

    bool IsEmpty()
    {
        return this->size_ == 0;
    }

    void Push(const int data)
    {
        Link* node = new Link(data, this->head_);
        this->head_ = node;
        ++this->size_;
    }

    bool Pop(int& data)
    {
        if (this->IsEmpty())
            return false;

        data = this->head_->data_;
        Link* tmp = this->head_;
        this->head_ = this->head_->next_;
        delete tmp;
        --this->size_;

        return true;
    }

private:
    int size_;
    Link* head_;
};

int main()
{
    Stack stack;

    for (int i = 0; i < 5; i++)
        stack.Push(i);

    int tmp;
    while (!stack.IsEmpty())
    {
        stack.Pop(tmp);
        cout << tmp << endl;
    }
    return 0;
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部