赞
踩
- #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 != ULL);
- 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;
- }
- class Stack
- {
- 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指针,即this = &back;
- }
-
- while(!stack.Empty())
- {
- stack.Pop(i);
- cout << i << " ";
- }
- return 0;
- }
优点:
避免函数名称冲突:因为都定义在类里面,别人定义的接口名称跟我们没关系
数据类型的扩充
数据封装:能够保护内部的数据结构不遭受外部的破坏,只能通过该类提供的接口来访问
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。