利用单向链表实现正整数转成字符串,代码如下:
#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;
}
正在学习编程,菜鸟一枚,搬砖能力还不是很强,多多包涵