/** * @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 将证书num转换为base指定的数制数 * @param[in] num 需要转换的整数 * @param[out] value 存储转换后的结果,以null结尾的字符串 * @param[in] base 待转换的数制类型 * @return 返回转换后的字符串 */ char* Convert(int num, char* value, const int base) { assert(value); Node* stack = InitStack(); while (num) { Push(stack, num % base); num = num / base; } int i = 0; int e = 0; while (stack->next != NULL) { Pop(stack, e); value[i++] = e + 0x30; } return value; } /** * @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) { char temp[15]; memset(temp, 0, 15); Convert(1348, temp, 2); cout<<temp<<endl; }