Add the following methods to the Array Bounded Stack class a
Solution
Program:
interface Stack<T> {
Stack<T> push(T ele) throws StackException;
T pop();
}
class StackException extends Exception
{
public StackException( String message )
{
super( message ); // Calls Exception\'s constructor
}
}
public class ArrayBoundedStack<T> implements Stack<T> {
private int total;
private Node first;
private class Node {
private T ele;
private Node next;
}
public ArrayBoundedStack() { }
public ArrayBoundedStack<T> push(T ele)
{
Node current = first;
first = new Node();
first.ele = ele;
first.next = current;
total++;
return this;
}
public T pop()
{
if (first == null)
try {
throw new StackException(\"Stack UnderFlow\");
} catch (StackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
T ele = first.ele;
first = first.next;
total--;
return ele;
}
public void popSome(int count)
{
for (int i = 0; i < count; i++) {
if (first == null)
try {
throw new StackException(\"Stack UnderFlow\");
} catch (StackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
T ele = first.ele;
first = first.next;
total--;
}
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
Node tmp = first;
while (tmp != null) {
sb.append(tmp.ele).append(\", \");
tmp = tmp.next;
}
return sb.toString();
}
public int getSize()
{
StringBuilder sb = new StringBuilder();
int size=0;
Node tmp = first;
while (tmp != null) {
size++;
tmp = tmp.next;
}
return size;
}
public boolean swapStart()
{
if(total <2)
return false;
else
{
Node tmp = first;
Node sec= tmp.next;
first.next=sec.next;
sec.next=first;
first=sec;
}
return true;
}
public static void main(String[] args) throws StackException {
ArrayBoundedStack<String> greeting = new ArrayBoundedStack<>();
greeting.push(\"!\").push(\"World\").push(\"Hello, \");
System.out.println(\"toString Method Called......Before Swapping : \"+greeting);
//Implementation Example Of swapStart() method
greeting.swapStart();
System.out.println(\"toString Method Called......After Swapping : \"+greeting);
//Implementation Example Of toString() method
System.out.println(\"toString Method Called : \"+greeting);
//Implementation of getting size of Stack
System.out.println(\"Size of Stack Is: \"+ greeting.getSize());
//Implementation method of pop method.
System.out.println(\"Pop Method Is Called\"+greeting.pop());
System.out.println(\"toString Method Called : \"+greeting);
//Implementation method of popSome method.
greeting.popSome(1);
System.out.println(\"toString Method Called : \"+greeting);
}
}
Output:
toString Method Called......Before Swapping : Hello, , World, !,
toString Method Called......After Swapping : World, Hello, , !,
toString Method Called : World, Hello, , !,
Size of Stack Is: 3
Pop Method Is CalledWorld
toString Method Called : Hello, , !,
toString Method Called : !,


