使用链栈实现数制的转换

/** * @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; }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值