forked from sanyathisside/Hacktoberfest2020
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Question_2.java
124 lines (95 loc) · 2.02 KB
/
Question_2.java
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
/*Q2. build a JAVA program from scratch that reverses the words in a sentence.*/
package questions;
import java.util.*;
public class Question_2 {
void reverse_Sentence_Brute(String s)
{
String reverse= "" ;
for(String temp : s.split(" ") )
{
for(int i=temp.length()-1;i>-1;i--)
{
reverse = reverse + temp.charAt(i);
}
reverse = reverse + " ";
}
System.out.println(reverse);
}
void reverese_Sentence_stack(String s)
{
Stack <String>stack = new Stack<String>();
String[] a = s.split(" ");
for(int i=0;i<a.length;i++)
{
stack.push(a[i]);
}
String reverse = "";
for(int i=0;i<a.length;i++)
{
reverse = reverse + stack.pop() +" ";
}
System.out.println (reverse);
}
int top = -1;
String [] stack ;
int max ;
public Question_2(int n )
{
max = n;
stack = new String[n];
}
void push(String enter)
{
if(top==-1)
{
top = 0;
stack[top] = enter;
}
else if(top == max-1)
{
System.out.print("Overflow!!!!!!");
}
else
{
top ++;
stack[top] = enter;
}
}
String pop()
{
String element;
if(top==-1)
{
System.out.println("Underflow");
return "";
}
else
{
element = stack[top];
top --;
return element;
}
}
String reverse(String s )
{
for(String temp : s.split(" "))
{
push(temp);
}
String reverse_string = "";
for(int i=s.split(" ").length-1;i>-1;i--)
{
reverse_string= reverse_string +pop() + " ";
}
return reverse_string;
}
public static void main(String... args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter the string you want to enter: ");
String sentence = scan.nextLine();
Question_2 reverse_sentence = new Question_2(sentence.length());
System.out.println(reverse_sentence.reverse(sentence));
reverse_sentence.reverese_Sentence_stack(scan.nextLine());
scan.close();}
}