File tree Expand file tree Collapse file tree 1 file changed +106
-0
lines changed Expand file tree Collapse file tree 1 file changed +106
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < iostream>
2
+ #include < string>
3
+
4
+ struct node
5
+ {
6
+ public:
7
+ char data;
8
+ node * next;
9
+
10
+ node (char data_t )
11
+ {
12
+ data = data_t ;
13
+ next = NULL ;
14
+ }
15
+ node ()
16
+ {
17
+ next = NULL ;
18
+ }
19
+ };
20
+
21
+ // simpe stack implementation using single linked list
22
+ class stack_char
23
+ {
24
+ private:
25
+ int count;
26
+ public:
27
+ node* head;
28
+ stack_char ()
29
+ {
30
+ head = NULL ;
31
+ count = 0 ;
32
+ }
33
+
34
+ void push (char data)
35
+ {
36
+ node* new_node = new node (data);
37
+ if (!new_node)
38
+ {
39
+ std::cout << " new failed " <<std::endl;
40
+ return ;
41
+ }
42
+ new_node->next = head;
43
+ head = new_node;
44
+ count++;
45
+ }
46
+
47
+ void pop ()
48
+ {
49
+ if (head == NULL ) {
50
+ return ;
51
+ }
52
+ node* temp = head;
53
+ head = head->next ;
54
+ delete temp;
55
+ count--;
56
+ }
57
+
58
+ char top ()
59
+ {
60
+ return head->data ;
61
+ }
62
+
63
+ bool isEmpty () {
64
+ return count == 0 ;
65
+ }
66
+
67
+ int size () {
68
+ return count;
69
+ }
70
+
71
+ // to be sure there is no memory leaks
72
+ ~stack_char ()
73
+ {
74
+ if (!isEmpty ())
75
+ {
76
+ for (int i = 0 ; i<size (); i++)
77
+ {
78
+ pop ();
79
+ }
80
+ }
81
+ }
82
+ };
83
+
84
+ std::string reverse_string (std::string to_be_reversed)
85
+ {
86
+ stack_char stack;
87
+ std::string reversed = " " ;
88
+ for (char c : to_be_reversed)
89
+ {
90
+ stack.push (c);
91
+ }
92
+
93
+ int original_stack_size = stack.size (); // save this before itself, as in pop the stack size keeps reducing
94
+ for (int i = 0 ; i < original_stack_size; i++)
95
+ {
96
+ reversed.push_back (stack.top ());
97
+ stack.pop ();
98
+ }
99
+ return reversed;
100
+ }
101
+
102
+ int main ()
103
+ {
104
+ std::cout << reverse_string (" Here is a string" );
105
+ return 0 ;
106
+ }
You can’t perform that action at this time.
0 commit comments