CSE131 Module 6: Solutions to Practice Problems

Be sure to ask if you are surprised by any of these answers.

  1. In the explanations below, if a is a LinkedList, then |a| is its length.
  2. LinkedList<Integer> pairwiseSum(LinkedList<Integer> list1, LinkedList<Integer> list2) {
      Iterator<Integer> iter1 = list1.iterator();
      Iterator<Integer> iter2 = list2.iterator();
      LinkedList<Integer> result = new LinkedList<Integer>();
      while (iter1.hasNext() || iter2.hasNext()) {
        int temp = 0;
        if (iter1.hasNext())
          temp += iter1.next();
        if (iter2.hasNext())
          temp += iter2.next();
        result.addLast(temp);
      }
      return result;
    }
    
  3. LinkedList<Object> reverse(LinkedList<Object> list) {
      Iterator<Object> listIter = list.iterator();
      LinkedList<Object> result = new LinkedList<Object>();
      while (listIter.hasNext())
        result.addFirst(listIter.next());
      return result;
    }
    

    or...

    LinkedList<Object> reverse(LinkedList<Object> list) {
      LinkedList<Object> result = new LinkedList<Object>();
      for (Object x : list)
        result.addFirst(x);
      return result;
    }
    
  4. LinkedList<Double> multiplyPosition(LinkedList<Double> list) {
      Iterator<Double> listIter = list.iterator();
      LinkedList<Double> result = new LinkedList<Double>();
      while (listIter.hasNext()) {
        result.addLast(listIter.next() * result.size());
      }
      return result;
    }
    

    or...

    LinkedList<Double> multiplyPosition(LinkedList<Double> list) {
      LinkedList<Double> result = new LinkedList<Double>();
      for (double d : list)
        result.addLast(d * result.size());
      return result;
    }