自定义栈数据结构,并且实现取出栈中最小元素

来源:互联网 发布:高德大数据 编辑:程序博客网 时间:2024/06/06 23:39

Stack.h

#include<iostream>using namespace std;const int success = 1;const int overflow = 2;const int underflow = 3;typedef int nodeEntry;struct stackGetMin{Stack temp;Stack minStack;void push(int item){temp.push(item);if(minStack.empty() || item<=minStack.top())minStack.push(item);}bool getMin(int &min){if(minStack.empty())return false;else{min = minStack.top();return true;}}};struct node{nodeEntry data;node *next;};class Stack{public:Stack::Stack();Stack::~Stack();bool Stack::empty();int Stack::size();int Stack::pop();int Stack::Min();nodeEntry Stack::top();int Stack::push(const nodeEntry &item);void Stack::operator = (const Stack &original);Stack::Stack(const Stack &original);protected:node *top_node;int count;int min;};bool Stack::empty(){return count == 0;}int Stack::pop(){if(top_node !=NULL){node *old_node = top_node;top_node = top_node->next;delete old_node;count--;return success;}return underflow;}int Stack::push(const nodeEntry &item){node *new_top = new node;if(new_top == NULL)return overflow;if(count == 0)min = item;elsemin = (min>item) ? item : min;new_top->data = item;new_top->next = top_node;count++;top_node = new_top;return success;}nodeEntry Stack::top(){if(top_node == NULL)return underflow;return top_node->data;}Stack::Stack(){top_node = NULL;count = 0;}Stack::~Stack(){while(count--)pop();}int Stack::size(){return count;}int Stack::Min(){return min;}void Stack::operator =(const Stack &original){node *new_top,*new_temp;node *original_node = original.top_node;if(original_node == NULL)new_top == NULL;else{new_top = new_temp = new node;new_top->data = new_temp->data = original_node->data;new_top->next = new_temp->next = NULL;while(original_node->next !=NULL){original_node = original_node->next;new_temp->next = new node;new_temp = new_temp->next;new_temp->data = original_node->data;new_temp->next = NULL;}}while(!empty())pop();top_node = new_top;}Stack::Stack(const Stack &original){node *new_copy,*new_copy_head;node *original_node = original.top_node;if(original_node == NULL)new_copy_head = NULL;else{new_copy = new_copy_head = new node;new_copy->data = new_copy_head->data = original_node->data;new_copy->next = new_copy_head->next = NULL;while(original_node->next != NULL){original_node = original_node->next;new_copy->next = new node;new_copy = new_copy->next;new_copy->data = original_node->data;new_copy->next = NULL;}}while(!empty())pop();top_node = new_copy_head;}

<test.cpp>

#include<iostream>#include<stdlib.h>#include"Stack.h"using namespace std;int main(){stackGetMin stackMin;stackMin.push(2);stackMin.push(2);stackMin.push(4);stackMin.push(3);stackMin.push(10);int min;stackMin.getMin(min);cout<<min<<endl;system("pause");return 0;}


0 0
原创粉丝点击