Complete the implementation of the instance methods size() and swap() within the
ID: 3854097 • Letter: C
Question
Complete the implementation of the instance methods size() and swap() within the class LinkedStack below. The method size() returns the number of elements that are currently stored into this stack The method swap exchanges the first two elements (not the values): the first clement 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 implements Stack { private class Elem {//Implements the nodes of the list private E info: private Elem next: private Elem(E info, Elem next) { this. info = info: this. next = next: } } private Elem top;//Instance variable, designates the top element public int size () {} public boolean swap() {} }Explanation / Answer
As this is linked list implementation of stack size() method can move on to next node from the top and count the number of node, here:
Elem<T> copy=top; //make a copy of top
int count=0; //count initialized to zero
while(copy!=null){ //while there is a node
count+=1; //add one to the counter
copy=copy.next; //move to the next node
}
return count;
swap() method will first check if there are less than 2 elements in the list, if it is then return false otherwise proceed. Make a copy of both the nodes and then exchange them.
if(top==null || top.next == null)
return false;
Elem<T> #making a copy
Elem<t> two = top.next;
one.next=two.next;
two.next=one;
top=two; #now top is second
return true;
For further doubts, feel free to comment and don't forget to upvote :)