简体   繁体   中英

Removing and adding items from a linked list (Java)

The code I wrote does not work when I try out the test cases but I can't understand why. My code is inside the 2 methods. If you need the rest of the class files you can find them here https://www.cs.berkeley.edu/~jrs/61b/hw/hw3/ . Note I edited the node class and created set and get methods. Could that be giving me errors or is my solution just wrong?

/**
*  squish() takes this list and, wherever two or more consecutive items are
*  equals(), it removes duplicate nodes so that only one consecutive copy
*  remains.  Hence, no two consecutive items in this list are equals() upon
*  completion of the procedure.
*
*  After squish() executes, the list may well be shorter than when squish()
*  began.  No extra items are added to make up for those removed.
*
*  For example, if the input list is [ 0 0 0 0 1 1 0 0 0 3 3 3 1 1 0 ], the
*  output list is [ 0 1 0 3 1 0 ].
*
*  IMPORTANT:  Be sure you use the equals() method, and not the "=="
*  operator, to compare items.
**/

public void squish() {
// Fill in your solution here.  (Ours is eleven lines long.)
  SListNode previous = head;
  SListNode next;
  SListNode root = head;
  int x = 1;

  for (int counter = 0; counter < size; counter++)
  {
      next = previous.getNext();
      if (!previous.equals(next))
      {
          root.setNext(next);
          root = next;
          x++;
      }
      previous = previous.getNext();

  }
  size = x;
}

/**
*  twin() takes this list and doubles its length by replacing each node
*  with two consecutive nodes referencing the same item.
*
*  For example, if the input list is [ 3 7 4 2 2 ], the
*  output list is [ 3 3 7 7 4 4 2 2 2 2 ].
*
*  IMPORTANT:  Do not try to make new copies of the items themselves.
*  Make new SListNodes, but just copy the references to the items.
**/

public void twin() {
 // Fill in your solution here.  (Ours is seven lines long.)
 SListNode previous = head;
 SListNode next;

 for (int counter = 0; counter < size; counter++)
 {
     next = previous.getNext();
     previous.setNext(previous);
     previous = previous.getNext();
     previous.setNext(next);
 }
 size = 2*size;
}

I think this might be a problem on the list length not getting updated upon completion. The test cases might look for that and print out an error message when you forget to do that! (No biscuits!)

I'm not sure though, but it seems to be the most plausible explanation (looking at the test file and seeing how they explicitly stated that they check all invariants).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM