-5

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;
    }
}
  • Your indentation is all over the place, making your code really hard to read. Maybe correcting that will also reveal any error. – GolezTrol Mar 16 '19 at 08:09
  • @GolezTrol done. sorry im new to using stackoverflow! – Muhammad Ali Tahir Mar 16 '19 at 08:10
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – DimaSan Mar 16 '19 at 08:49

2 Answers2

0

Move this line curr = curr.next to the last line of the loop:

while(curr != null)
{
    if ((int)curr.getValue() % 2 == 0)
    {
        odds.enqueue(((int)curr.getValue()));
    }
    curr = curr.next;
}
Yingkai
  • 28
  • 5
  • Got it! Thank you. Also could you go over the logic of my code ? i would appreciate your input on it as im getting the wrong output, trying to debug at it as we speak! not getting the null pointer anymore though. – Muhammad Ali Tahir Mar 16 '19 at 08:16
  • 1. You shouldn't use queue. The data in queue will be lost once it pull out. You can use an ArrayList instead. 2. 'num++' is wrong, you want the second number in the 'queue', but 'num++' is the value of first number in queue (the 'num') plus 1. – Yingkai Mar 16 '19 at 08:34
  • What's the programming language did you use? Your code looks like Java language, but much of the code are wrong for Java. e.g. list.length() is wrong, the correct form is list.size(). – Yingkai Mar 16 '19 at 08:37
0

I did not understand how the output you showed has one of the numbers multiplied by 100 in each element of String array. Based on my understanding of your question here is a solution.

import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Shifts {

    public static void main(String[] args) {
        LinkedList<Integer> list = Arrays.asList(1, 2, 15, 14, 23)
                .stream().filter(i -> i % 2 != 0)
                .collect(Collectors.toCollection(LinkedList::new));
        int oddCount = list.size();
        String[] results = new String[oddCount];
        IntStream.range(0, oddCount).forEach(index -> {
            Collections.rotate(list, 1);
            results[index] = list.stream()
                             .map(i -> i.toString())
                             .collect(Collectors.joining(","));
        });
        Arrays.asList(results).stream().forEach(System.out::println);
    }

}

Drawing from your code, and since you are allowed to use Queue, here is refined giveShifts method

public static String[] giveShifts(LinkedList<Integer> list) {
        //since you need only odd numbers, filter out even ones
        list = list.stream().filter(i -> i % 2 != 0)
                .collect(Collectors.toCollection(LinkedList::new));
        int oddCount = list.size();
        String[] result = new String[oddCount];
        //type cast it to Queue as it will help understand the concept
        // shift is essentially, remove from head and add to tail in queue
        java.util.Queue<Integer> queue = list;
        for(int i=0;i<oddCount; i++){
            queue.add(queue.remove());
            result[i] = queue.stream()
                       .map(element -> element.toString())
                       .collect(Collectors.joining(","));
        }
        return result;
    }
Gro
  • 1,613
  • 1
  • 13
  • 19
  • unfortunately i am only allowed to use stacks or queues to implement this. Ive edited my question to use a stack. if you could go over and help me fix this! – Muhammad Ali Tahir Mar 16 '19 at 09:09
  • Your code doesn't compile. If you have used java.util.LinkedList as parameter then methods like length() or member variables like head don't exist. Statements like StackInt odds = new StackInt(list.size()); or Node curr = list.head; seem to be referring to the classes that you have not shared. Incorrect API use and unknown classes are making it difficult to follow your code. – Gro Mar 16 '19 at 10:32
  • Since you are allowed to use queue, drawing bits and pieces from your code, I have reimplemented your method giveShifts in the solution. I have used Java8 syntax to reduce lines of code. You can take an exercise of replacing loops and Lamdas should you want a Java7 or lower solution – Gro Mar 17 '19 at 03:23