之前对顺序栈写了基本操作,认为有必要也动手练练栈的链表实现。
对于链栈,一般不会出现栈满的情况。
链栈头文件定义例如以下:
#ifndef CSTOCK_H_ #define CSTOCK_H_ typedef int elemType; struct Item { elemType data; Item * p_next; }; class CStock { public: CStock(); CStock(const CStock & otherStock); //拷贝构造函数; CStock & operator = (const CStock & otherStock); //=运算符重载。 void push(elemType x);//进栈操作; bool pop(elemType &x); //出栈操作; bool isEmpty() const; //推断栈空; void clear();//清空栈。使栈为空; int size() const; //获得栈的大小。 void print() const; //打印栈内元素; ~CStock(); public: Item *p_Top;//栈顶 }; #endif
#include "CStock.h" #include <iostream> using std::cout; using std::endl; CStock::CStock(): p_Top(NULL)//构造函数 { } //拷贝构造函数 便于定义时初始化,如 CStock s1 = stock; 默认的会出现潜在问题 CStock::CStock(const CStock & otherStock):p_Top(NULL) { *this = otherStock; } // =运算符重载,便于赋值,如:CStock s1; .... CStock s2; s2 = s1; 默认的会出现潜在问题。我写的这种方法认为不好,有好的写法希望大神能指导指导。 CStock & CStock::operator =(const CStock & otherStock) { CStock tempStock; Item * copyElement = otherStock.p_Top; //将栈otherStock的元素出栈,依次进入tempStock内,元素的位置顺序和otherStock相反; while(copyElement) { tempStock.push(copyElement->data); copyElement = copyElement->p_next; } copyElement = tempStock.p_Top; //将tempStock的元素出栈,依次进入此栈内,元素位置和otherStock同样。 while(copyElement) { push(copyElement->data); copyElement = copyElement->p_next; } return *this; } //进栈操作 void CStock::push(elemType x) { Item * pushElement = new Item; pushElement->data = x; if(!p_Top)//假设栈为空时 { p_Top = pushElement; pushElement->p_next = NULL; } else //若栈不为空时 { pushElement->p_next = p_Top; p_Top = pushElement; } } //出栈操作,若栈不为空。数据有形參x带至主调函数,出栈失败函数返回false; bool CStock::pop(elemType &x) { if(!p_Top) { return false; } x = p_Top->data; p_Top = p_Top->p_next; return true; } //推断栈是否为空 bool CStock::isEmpty() const { return p_Top == NULL; } //清空栈,使栈置为空栈 void CStock::clear() { Item * deleteElement; while(p_Top) { deleteElement = p_Top; p_Top = p_Top->p_next; delete deleteElement; } } //获得栈的大小 int CStock::size() const { int length = 0; Item *temp = p_Top; while(temp && ++length) { temp = temp->p_next; } return length; } //打印栈内元素 void CStock::print() const { int count = 0; Item * temp = p_Top; while(temp && ++count) { cout << temp->data << " "; if(count % 5 == 0) cout << endl; temp = temp->p_next; } } //析构函数,提供对指针成员的释放,默认的会出现潜在问题 CStock::~CStock(void) { Item * deleteElement; while(p_Top) { deleteElement = p_Top; p_Top = p_Top->p_next; delete deleteElement; } }