标签:c++ primer c++ 类与数据抽象
下面通过分别用C和C++来实现一个链栈(链表实现),从中体会数据封装抽象的思想:
【C++实现】
#include <iostream> using namespace std; class Stack { private: struct Link { int data_; Link *next_; Link(int data, Link *next) : data_(data), next_(next) { } }; public: Stack() : head_(0), size_(0) { } ~Stack() { Link *tmp; while (head_) { tmp = head_; head_ = head_->next_; delete tmp; } } void Push(const int data) { Link *node = new Link(data, head_); head_ = node; ++size_; } bool Empty() { return (size_ == 0); } bool Pop() { if (Empty()) { return false; } Link *tmp = head_; head_ = head_->next_; delete tmp; --size_; return true; } int Top() { if (Empty()) { return false; } return head_->data_; } private: Link *head_; int size_; }; int main(void) { Stack stack; int i; for (i = 0; i < 5; i++) { stack.Push(i); } while (!stack.Empty()) { cout << stack.Top() << " "; stack.Pop(); } cout << endl; return 0; }
运行结果:
4 3 2 1 0
【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 StackInit(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; free(tmp); --stack->size; 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(void) { struct Stack stack; StackInit(&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++ primer 第四版
Effective C++ 3rd
http://blog.csdn.net/jnu_simba/article/details/9284587
http://blog.csdn.net/zjf280441589/article/details/24671691
C++编程规范
版权声明:本文为博主原创文章,未经博主允许不得转载。
C++ Primer 学习笔记_26_类与数据抽象(12)--分别用C和C++来实现一个链栈
标签:c++ primer c++ 类与数据抽象
原文地址:http://blog.csdn.net/keyyuanxin/article/details/47276865