利用链表实现正整数转成字符串

利用单向链表实现正整数转成字符串,代码如下:

#include<iostream>
using namespace std;
struct LinkNode
{
    short int data;
    LinkNode *next;
};
struct cLinkNode
{
    char data;
    cLinkNode *next;
};
//创建int char类型单向链表
LinkNode * i_CreateList(int n)
{
    int x = n;
    LinkNode * head = NULL, *temp = NULL;
    int m = 1,b;
    head = new LinkNode;
    while (x)
    {
        if (m == 1)
        {
            if (head != NULL)
            {
                b = x % 10;
                head->data = b;
                head->next = NULL;
                temp = head;
                m++;
            }   
        }
        else
        {
            b = x % 10;
            LinkNode *p = new LinkNode;
            if (p != NULL)
            {
                p->data = b;
                p->next = NULL;
                temp->next = p;
                temp = p;
                m++;
            }

        }
        x = x / 10;
    }
    return head;
}
cLinkNode * c_CreateList(int n)
{
    int x = n;
    int m = 1;
    LinkNode * put = i_CreateList(x);
    cLinkNode * head = NULL, *temp = NULL;
    head = new cLinkNode();
    while (put)
    {
        if (m == 1)
        {
            if (head != NULL)
            {
                head->data = put->data + '0';
                head->next = NULL;
                temp = head;    
            }
        }
        else
        {
            cLinkNode *p = new cLinkNode;
            if (p != NULL)
            {
                p->data = put->data + '0';
                p->next = NULL;
                temp->next = p;
                temp = p;
            }
        }
        m++;
        put = put->next;
    }
    return head;
}
int LengthNode(cLinkNode *head)
{
    int num = 0;
    cLinkNode *p = head;
    while (p)
    {
        num++;
        p = p->next;
    }
    return num-1;
}
void Traverse(cLinkNode *head)
{
    cLinkNode *p = head;
    int n = LengthNode(p);
    char s[1001];
    int i = 0;
    while (p)
    {
        s[i] = p->data;
        p = p->next;
        i++;
    }
    for (i = 0; i<=n/2;i++)
    {
        char c;
        c = s[i];
        s[i] = s[n-i];
        s[n-i] = c;
    }
    s[n+1] = '\0';
    cout << "string=" << s;
    cout << endl;
}
int main()
{
    int n;
    cout << "Input n:";
    cin >> n;
    cLinkNode * head1=c_CreateList(n);
    Traverse(head1);
    return 0;
}

正在学习编程,菜鸟一枚,搬砖能力还不是很强,多多包涵

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值