Skip to content

Commit 5fba5ed

Browse files
authored
Merge pull request #32 from ShehaniHettiarachchi/DataStructure
Data structure reverse method using stack
2 parents 4997348 + 5652731 commit 5fba5ed

File tree

2 files changed

+94
-0
lines changed

2 files changed

+94
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package Stack;
2+
3+
import java.util.Scanner;
4+
5+
public class Reverser {
6+
private String input,output;
7+
8+
Reverser(String input){
9+
this.input = input;
10+
output = "";
11+
}
12+
13+
public String reverse(){
14+
StackX stack = new StackX(input.length());
15+
16+
for (char letter : input.toCharArray()) {
17+
stack.push(letter);
18+
}
19+
20+
21+
22+
while (!stack.isEmpty()) {
23+
output += stack.pop();
24+
25+
}
26+
27+
return output;
28+
}
29+
30+
public static void main(String[] args) {
31+
Scanner sc = new Scanner(System.in);
32+
System.out.print("Enter any text : ");
33+
String str = sc.nextLine();
34+
Reverser obj = new Reverser(str);
35+
System.out.println("Reversed :" + obj.reverse());
36+
sc.close();
37+
}
38+
}
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package Stack;
2+
3+
public class StackX {
4+
private char[] data; //stack array
5+
private int top; //top of the stack
6+
private int size; //size of stack array
7+
8+
public StackX(int size){
9+
this.size = size;
10+
data = new char[size];
11+
top = -1;
12+
}
13+
14+
//push method
15+
public boolean push(char element){
16+
if (top < size - 1) {
17+
data[++top] = element;
18+
return true;
19+
}
20+
21+
return false;
22+
23+
}
24+
25+
public char pop(){
26+
if (top != -1) {
27+
return data[top--];
28+
}
29+
30+
return ' ';
31+
}
32+
33+
public char peek(){
34+
if (top != -1) {
35+
return data[top];
36+
}
37+
38+
return ' ';
39+
}
40+
41+
public boolean isFull(){
42+
if (top == size - 1) {
43+
return true;
44+
}
45+
46+
return false;
47+
}
48+
49+
public boolean isEmpty(){
50+
if (top == -1) {
51+
return true;
52+
}
53+
54+
return false;
55+
}
56+
}

0 commit comments

Comments
 (0)