I need help writing a method for Java It should perform a swapping of the head a
ID: 3810534 • Letter: I
Question
I need help writing a method for Java
It should perform a swapping of the head and the tail nodes in a list that has more than one element
the current position is required to swap if its pointing to the head or tail node
method does not require input arguments
this is pseudo code that I have
public boolean swapHeadandTail()
{
If size > 1 then
1. Find the tail node by traversing the list to get to the tail node
2. Get Head’s and Tail’s elements via getElement method
3. Exchange the data values using setElement method
4. Return true status
}
Explanation / Answer
HI, Please find my implementation.
public boolean swapHeadandTail()
{
if(size <= 1)
return false;
Entry<E> temp = head;
// now making temp to point to tail
while(temp.getNext() != null)
temp = temp.getNext();
// now exchanging head data and tail data
E e = temp.getElement();
temp.setElement(head.getElement());
head.setElement(e);
return true
}