Home reverseString.cpp
Post
Cancel

reverseString.cpp

reverseString.cpp

Go Back

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// Link to Challenge: https://edabit.com/challenge/HXGx9oXukEgsFK6PH

#include <iostream>
#include <cstring>

using namespace std;

class ReverseString{
    private:

        string val = "";
        struct node{
            string data;
            node* next;
        };

        node* head = nullptr;

    public:

        ReverseString();

        ReverseString(string givenString){
            val = givenString;
        }

        void reverse(){
            for (int i = 0; i < val.size(); i++){
                string tmp = val.substr(i, 1);
                if (head == nullptr){
                    head = new node{tmp, nullptr};
                }
                else{
                    head = new node{tmp, head};
                }
            }
            string tmp = "";
            for (node* i = head; i != nullptr; i = i -> next){
                tmp += i -> data;
            }
            val = tmp;
        }

        void print(){
            cout << val << endl;
        }

};

int main(){
    ReverseString theString("Hello World!");
    theString.print();
    theString.reverse();
    theString.print();
}

Console Output:

1
2
Hello World!
!dlroW olleH

Go Back

This post is licensed under CC BY 4.0 by the author.