Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

java problems Question 3 Implement the class method: public static <E> void swap

ID: 3854016 • Letter: J

Question

java problems

Question 3

Implement the class method:
public static <E> void swap(Stack<E> xs , Stack<E> ys)

The method exchanges the content of two stacks, xs and ys.

ThemethodmustworkforanyvalidimplementationoftheinterfaceStack;

You can assume the existence of the classes DynamicArrayStack and LinkedStack.

Stack<String> a, b;
a = new LinkedStack<String >();
a . push (” alpha ” ) ;
a . push (” beta ” ) ;
a.push(”gamma”);
b = new DynamicArrayStack<String >(); b . push (” blue ” ) ;
b . push (” green ” ) ;
b.push(”yellow ”);
b.push(”black ”);
System . out . p r i n t l n ( a ) ;
System.out. println(b);

swap(a, b);
System . out . p r i n t l n ( a ) ; System.out. println(b);

In particular, the above statements should print the following.

[gamma, beta , alpha ]
[ black , yellow , green , blue ]

[ black , yellow , green , blue ]

[gamma, beta , alpha ]

Write the code for this method with the following signature:
public static <E> void swap(Stack<E> xs , Stack<E> ys) {}

Question 4

Complete the implementation of the instance methods size() and swap() within the class LinkedStack below.

Themethodsize()returnsthenumberofelementsthatarecurrentlystored into this stack

The method swap exchanges the first two elements (not the values); the first element becomes the second and the second element becomes the first. The method returns false if there are less than 2 elements in the list. You cannot use the methods push and pop, instead the links of the structure (references) must be transformed.

public class LinkedStack<T> implements Stack<T> {

private class Elem<E> { // Implements the nodes of the list private E info ;

private Elem<E> next;

private Elem(E info , Elem<E> next) { this.info=info;
this.next = next;

} }

private Elem<T> top; // Instance variable , designates the top element

public int size () {}

public boolean swap() {} }

Explanation / Answer

class TwoStacks
{
int size;
int top1, top2;
int arr[];
TwoStacks(int n)
{
arr = new int[n];
size = n;
top1 = -1;
top2 = size;
}
void push1(int x)
{
if (top1 < top2 - 1)
{
top1++;
arr[top1] = x;
}
else
{
System.out.println("Stack Overflow");
System.exit(1);
}
}
void push2(int x)
{
if (top1 < top2 -1)
{
top2--;
arr[top2] = x;
}
else
{
System.out.println("Stack Overflow");
System.exit(1);
}
}
int pop1()
{
if (top1 >= 0)
{
int x = arr[top1];
top1--;
return x;
}
else
{
System.out.println("Stack Underflow");
System.exit(1);
}
return 0;
}
int pop2()
{
if(top2 < size)
{
int x =arr[top2];
top2++;
return x;
}
else
{
System.out.println("Stack Underflow");
System.exit(1);
}
return 0;
}