Converting integer into linked list 321 to 3->2->1

closed account (ShqoT05o)
How can I take a string convert into integer and make the integer into a linked liked 3->2->1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
 #include <iostream>

using namespace std;

struct Node{
    int data;
    Node *next;
};
class Integer{
    private:
        Node *head;
        Node *tail;

    public:
        Integer() {
            head = NULL;
            tail = NULL;
        }
    void generate(string s);
  
};
    
    void Integer::generate(string s){
        int n =stoi(s);
        
    }
 


    
int main(){
        Integer B;
        B.generate("321");
        B.show();
    
        
          return 0;
}
Last edited on
don't do it that way, its the hard way to solve it.

take the string, peel off the characters, and directly convert (char - '0' in ascii turns a letter to its digit value for 0-9).
so you get "1234" then take the letter '1' and directly turn that into '1' then put it in the list, or go backwards do 4 first, whatever order.

the way you propose it you convert to a number, then have to peel off the digits (%10 can do this of course) and then put it in the list, almost but not quite going text to int back to near- text to list instead of just text to list of ints directly.
Last edited on
See my post in your previous thread http://www.cplusplus.com/forum/beginner/277556/

Rather than node data being of type char, just have data of type int and do a simple conversion from char digit to its int (if a char digit subtract '0').
1
2
3
4
5
6
7
8
9
void Integer::generate(string s)
{
    for ( char c : s ) tail = ( head ? tail->next : head ) = new Node{ c - '0', nullptr };
}
 
void Integer::show()
{
    for ( Node *n = head; n; n = n->next ) cout << n->data << ' ';
}
Topic archived. No new replies allowed.