#pragma once #include二、链接栈的实现(linkStack.h)using namespace std; template class LinearStack { public: LinearStack(int LSMaxSize) { MaxSize = LSMaxSize; element = new T[LSMaxSize]; top = -1; } ~LinearStack() { delete[]element; } bool IsEmpty()//栈空返回true,非空返回false { return top == -1; } bool IsFull()//栈满返回true,不满返回false { return top + 1 == MaxSize; } int GetElementNumber()//求栈中元素的个数 { return top + 1; } bool Push(const T&x)//在栈顶插入元素x,成功返回true,失败返回false { if(IsFull()) return false; else { top++; element[top] = x; return true; } } bool Top(T&x)//求栈顶元素的值放入x中,成功返回true,失败返回false { if (IsEmpty()) return false; else { x = element[top]; return true; } } bool Pop(T&x)//从栈顶删除一个元素,并将该元素的值放入x中 { if (IsEmpty()) return false; else { x = element[top]; top--; return true; } } void OutPut(ostream& out)const//将顺序栈放到输出流out中输出 { for (int i = 0; i <= top; i++) out << element[i] << endl; } private: int top;//用来表示栈顶 int MaxSize;//栈中最大元素个数 T* element;//一维动态数组 }; //重载插入运算符<< template ostream& operator<<(ostream& out, const LinearStack &x) { x.OutPut(out); return out; }
#pragma once #includeusing namespace std; template //结点类 class linkNode { template friend class linkStack;//将链接栈声明为友类 public: linkNode()//构造函数 { next = NULL; } private: T data;//结点元素 linkNode *next;//指向下一个结点的指针 }; //链接栈类 template class linkStack { public: linkStack()//构造函数,创建空栈 { top = NULL; size = 0; } ~linkStack()//析构函数,删除栈 { T x; while (top != NULL)//栈非空则元素依次出栈 Pop(x); } bool IsEmpty()const//判断栈是否为空 { return top == NULL; } bool Push(const T&x)//在栈顶插入元素x { linkNode *p = new linkNode ; if (p == NULL)//如果内存没空间了,或者创建创建失败返回false return false; else { p->data = x;//为元素赋值 p->data = top;//将新结点插入栈顶 top = p;//top指向栈顶 size++; return true; } } bool Top(T&x)//求栈顶元素的值放入x中 { if (IsEmpty()) return false; else { x = top->data; return true; } } bool Pop(T&x)//从栈顶删除一个元素,并将该元素的值放入x中 { linkNode *p; if (IsEmpty()) return false; else { x = top->data;//删除元素的值放入x中 p = top;//得到待删除节点的指针 top = top->next;//top指向新的栈顶 delete p;//元素出栈 size--; return true; } } void OutPut(ostream& out)const//将顺序栈放到输出流out中输出 { linkNode *p; p = top; for (int i = 0; i < size; i++) { out << p->data << endl; p = p->next; } } private: linkNode *top;//指向链接链的栈顶结点的指针 int size;//栈中元素个数 }; //重载插入运算符 template ostream& operator<<(ostream& out, const linkStack & x) { x.OutPut(out); return out; }
三、应用
#includeusing namespace std; #include"LinearStack.h" void conversion(int n, int base)//转换函数 { int x, y; y = n; LinearStack s(100); while (y) { s.Push(y%base); y = y / base; } cout << "十进制数" << n << "转换为" << base << "进制为:n"; while (!s.IsEmpty()) { s.Pop(x); cout << x; } } int main() { int n, base; cout << "请输入十进制数和要转换的进制的基数:n" << endl; cin >> n >> base; conversion(n, base); cout << endl; system("pause"); return 0; }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)