Home > Software engineering >  Changing an element of Queue without a temporary list, queue or other data structure
Changing an element of Queue without a temporary list, queue or other data structure

Time:11-07

Doing exercises from the book Java Methods by Litvin. One problem asks to create a LinkedList that implements the Queue interface.

A Morse code message is represented in a program as a queue of strings. Each string consists of dots and dashes. Write and test a method that replaces each question mark (represented by "..--..") with a period (".-.-.-"), leaving all other codes unchanged. Do not use any temporary lists, queues, or other data structures.

Since the LinkedList implements a Queue, I am unable to use the ListIterator. I'm unsure as to how to change the values of the elements in the Queue without placing them in a temporary place. How would I go about solving this problem?

CodePudding user response:

The question could use some code to show your current state of work. But without further information:

  1. A queue only grants you access to the first element by design of FIFO.
  2. You can always remove the first element and insert it at the back.
  3. If you do that for all elements in the queue without changing each element, the queue ends up in the same state as before.

Hence, this would be a possible solution with only using the Queue interface:

public void replaceQuestionmarks(Queue<String> input) {
  for(int i = 0; i<input.size(); input  ) {
    String current = input.remove();
    input.add(questionMarkToPeriod(current));
}

"questionMarkToPeriod" would be a method for the conditional replacement.

Edit: Forgot the generic type in Queue.

CodePudding user response:

Thanks to @StephenC and @tgdavies I figured out the problem. After casting the LinkedList, I was able to use the ListIterator and update the values from there

public static void replace(Queue<String> morseCode)
    {
        ListIterator<String> iter = ((LinkedList<String>)(morseCode)).listIterator();
        while(iter.hasNext())
        {
            if(iter.next() == "..--..")
            {
                iter.set(".-.-.-");
            }
            
        }
    }

Will try to make my questions more understandable in the future.

  • Related