分别用C和C++来实现一个链栈
下面通过分别用C和C++来实现一个链栈(链表实现),从中体会数据封装抽象的思想:
C语言实现:
C++ Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
#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++实现:
C++ Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
#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(int &data) { if (Empty()) { return false; } Link *tmp = head_; data = head_->data_; head_ = head_->next_; delete tmp; --size_; return true; } private: Link *head_; int size_; }; // 避免名称冲突 // 类型的扩充 // 数据封装、能够保护内部的数据结构不遭受外界破坏 int main(void) { Stack stack; // 抽象数据类型 类类型 int i; for (i = 0; i < 5; i++) { stack.Push(i); // this = &stack } while (!stack.Empty()) { stack.Pop(i); cout << i << " "; } cout << endl; return 0; } |
输出都是一致的,对比不同的写法,可以体会两种语言的一些不同之处,当然这只是比较显而易见的方面了。
参考:
C++ primer 第四版
Effective C++ 3rd
C++编程规范