Merge Queues V45106


Statement
 

pdf   zip   tar

thehtml

In the public_files section of the problem statement, a class called LinkedQueue, which implements the Queue ADT using a singly-linked list, is defined. Extend the implementation of this class with a new public method merge(self, other). This method merges the elements of two queues q1 and q2 as follows: If q1 represents the queue e1, e2, …, en and q2 represents the queue o1, o2, …, om, after executing q1.merge(q2) queue q1 represents

  • the queue e1,o1,e2,o2,...en,on,on+1,…,om, if nm; or
  • the queue e1,o1,e2,o2,...em,om,em+1,…,en, if n > m.

In both cases, after executing q1.merge(q2), the queue q2 is empty, because its elements have been transferred to q1.

For example, if q1 is an instance of the class LinkedQueue that represents the queue

front 1, 3, 5, 7 back

and q2 is an instance of the class LinkedQueue that represents the queue

front 2, 4, 6 back

after executing the statement q1.merge(q2), q1 will represent the queue

front 1, 2, 3, 4, 5, 6, 7 back

and q2 will be empty.

Your implementation of merge(self, other) should not use any public method of the class LinkedQueue. It should work direclty with the representation of the class (i.e. attributes of the classes LinkedQueue and _Node), and it should not create any new node.

You should also override the special method __str__ of the class LinkedQueue so that the contents of an instance of this class representing a queue of integer numbers can be printed without making any call to the public method dequeue.

In particular, you should add the following public methods to the LinkedQueue class:

  def merge(self, other):
    # Insert your implementation below


  def __str__(self):
    # In the implementation of this method, assume the queue instance
    # can only contain integer numbers. This is only true in the context
    # of this problem.
    # Insert your implementation below
Public test cases
  • Input

    1 3 5 7
    2 4 6

    Output

    v[0]: 1 3 5 7
    v[1]: 2 4 6
    After calling v[0].merge(v[1])
    v[0]: 1 2 3 4 5 6 7
    v[1]: 
    
  • Information
    Author
    Language
    English
    Official solutions
    Python
    User solutions
    Python