终于在长时间的努力之后实现了对原来栈代码的优化,这次数据的插入与删除比原先的代码不知道快了多少,
将原来在链表末尾的插入删除替换成了在链表头的(还是拜网上的一个说明所赐,连接地址:
http://sjjp.tjuci.edu.cn/sjjg/datastructure/ds/web/zhanhuoduilie/zhanhuoduilie3.1.3.htm
真的非常感谢!!!点击打开链接)
而且数据的通用性也大为提高,再一次将他推荐到首页上,希望能够对大家有用,还是那句话,不妥之处,欢迎拍砖哈.....
代码实现:
#include <iostream> #include <iomanip> using namespace std; enum status {success,fail,underflow,overflow,range_error}; typedef int SElemType; class Node { public: SElemType data; Node *next; }; class LinkStack { private: Node *rear; protected: int count; public: LinkStack(); ~LinkStack(); status push(const SElemType &item); status pop(void); status clear(void); bool empty(void) const; int length(void) const; status front(SElemType &item) const; status traverse(void) const; }; LinkStack::LinkStack() { rear = new Node; rear = NULL; count = 0; } LinkStack::~LinkStack() { clear(); delete rear; count = 0; } status LinkStack::push(const SElemType &item) { Node *newnode = new Node; newnode -> data = item; newnode -> next = rear; rear = newnode; count ++; return success; } status LinkStack::pop(void) { Node *searchp = rear; rear = searchp -> next; delete searchp; count--; return success; } status LinkStack::clear(void) { Node *searchp = rear; Node *followp = searchp; while (searchp) { followp = searchp; searchp = searchp -> next; delete followp; } rear = NULL; count = 0; return success; } bool LinkStack::empty(void) const { return (count == 0); } int LinkStack::length(void) const { return count; } status LinkStack::front(SElemType &item) const { if (empty()) return range_error; item = rear -> data; return success; } status LinkStack::traverse(void) const { if (empty()) { cout << "Stack is empty!" << endl; return underflow; } Node *searchp = rear; cout << "All data:"; while (searchp) { cout << ' ' << setw(3) << searchp -> data; searchp = searchp -> next; } cout << endl; return success; } int main() { cout << "Push:" << endl; LinkStack S; for (int i = 0; i < 10; i++) S.push( i); S.traverse(); cout << "\nThe data's number:" << S.length() << '\n' << endl; int item; S.front(item); cout << "The fist data is: " << item << endl; cout << endl; S.pop(); S.front(item); cout << "After pop,The fist data is: " << item << endl; cout << "The data's number:" << S.length() << '\n' << endl; S.clear(); cout << "After clear,The data's number:" << S.length() << endl; S.traverse(); cout << "\nEmpty? "; S.empty() ? cout << "Yes!" << endl : cout << "No!" << endl; }
运行截图: