/** * @brief 链式栈的表示与实现 * @author wlq_729@163.com * http://blog.csdn.net/rabbit729 * @version 1.0 * @date 2009-03-10 */ #include <assert.h> #include <iostream> using namespace std; struct Node { int Data; struct Node* next; }; /** * @brief 初始化栈 * @return 返回栈头指针 */ Node* InitStack() { Node* head = new Node; assert(head); head->next = NULL; return head; } /** * @brief 链式栈的建立 * @return 返回链式栈的头指针 */ Node* CreateLinkStack() { Node* head = new Node; assert(head); head->next = NULL; Node* p = head; int data = 0; bool bInPuts = true; while (bInPuts) { cin>>data; if (0 == data) { bInPuts = false; } else { Node* node = new Node; assert(node); node->Data = data; node->next = p->next; p->next = node; } } return head; } /** * @brief 元素e入栈 * @param[in] head 栈头指针 * @param[in] e 入栈元素 * @return 返回操作结果 * -0 操作成功 * --1 操作失败 */ int Push(Node* head, const int e) { assert(head); Node* p = new Node; if (NULL == p) { cout<<"apply memory error!"<<endl; return -1; } p->Data = e; p->next = head->next; head->next = p; return 0; } /** * @brief 元素出栈 * @param[in] head 链式栈指针 * @param[out] e 出栈元素 * @return 返回操作结果 * -0 操作成功 * --1 操作失败 */ int Pop(Node* head, int& e) { assert(head); Node* p = head->next; e = p->Data; head->next = p->next; delete p; p = NULL; return 0; } /** * @brief 获取栈中元素个数 * @param[in] head 栈头指针 * @return 返回栈中元素个数 */ int GetLength(Node* head) { assert(head); int num = 0; Node* p = head->next; while (p != NULL) { num++; p = p->next; } return num; } /** * @brief 打印链表元素 * @param[in] head 栈头指针 */ void Show(Node* head) { Node* p = head->next; while (p != NULL) { cout<<p->Data<<endl; p = p->next; } } void main(void) { Node* head = CreateLinkStack(); Show(head); Push(head, 10); Show(head); int e = 0; Pop(head, e); Show(head); cout<<e<<endl; }
posted on 2009-03-12 11:12 张云临 阅读(167) 评论(0) 编辑 收藏 举报