I'm trying to code this problem.
Assume you are given a linked list formed by n nodes such that each node stores an integer. Write an efficient Java code that prints all circular shifts of the odd numbers in the linked list in array of n strings. For example, if the list is 1 → 2 → 15 → 14 → 23, the output will be an array str of strings such that
str [0] = “1, 15, 2300
, str [1] = “15, 23, 1
00, and str [2] = “23, 1, 1500.
Note that the numbers are separated by ‘,’ and there is no space between them. You need to create a class named Shifts which has the following method:
public static String[]
giveShifts (LinkedList<Integer> list)
. Here list is a linked list that maintains integers
Ive tried debugging my code but to no avail. It goes through all the nodes and once it gets to the last node, the value is null. im not too sure why.
import java.util.Arrays;
public class Shifts
{
public static String[] giveShifts(LinkedList<Integer> list)
{
String[] result = new String[list.length()];
StackInt odds = new StackInt(list.length());
Node curr = list.head;
while(curr != null)
{
if ((Integer)curr.getValue() % 2 == 0)
{
odds.push(((int)curr.getValue()));
}
curr = curr.next;
}
int[] nums = new int[list.length()];
String numsStr = "";
while(!odds.isEmpty())
{
for(int i=0; i<result.length; i++)
{
nums[i] = odds.pop();
}
numsStr = Arrays.toString(nums);
for(int j=0; j<result.length; j++)
{
result[j] = numsStr;
}
}
return result;
}
}