Question

Java/LinkedList Need help with a few of the TODO parts, more info below in comments in...

Java/LinkedList Need help with a few of the TODO parts, more info below in comments in bold.

Thanks,

package lab4;

import java.util.IdentityHashMap;

public class IntNode implements Cloneable {
   private int data;
   private IntNode next;
  
   public IntNode(int d, IntNode n) {
       data = d;
       next = n;
   }
  
   public IntNode getNext() {
       return next;
   }
  
  
   /// Override methods from Object
  
   @Override
   public boolean equals(Object obj) {
       throw new UnsupportedOperationException("Don't use .equals to compare nodes!");
   }
  
   @Override
   public IntNode clone() {
       try {
           return (IntNode)super.clone();
       } catch (CloneNotSupportedException e) {
           throw new AssertionError("IntNodes should be cloneable!");
       }
   }
  
   protected String originalToString() {
       return super.toString();
   }
  
   @Override
   public String toString() {
       String nextString = "null";
       if (next != null) nextString = next.originalToString();
       return super.toString() + "(" + data + "." + nextString + ")";
   }
  
  
   /// Print method that is used for testing
   /**
   * Convert a list to a string for debugging purposes.
   * The string is of the form [n1, n2, n3, ...].
   * if the list ends in a cycle then we have "..." followed by
   * the one-based index of the node we go back to.
   * @param head list t print, may be null
   * @return string representation of the whole list.
   */
   public static String listToString(IntNode head) {
       if (head == null) return "[]";
       IdentityHashMap<IntNode,Integer> m = new IdentityHashMap<>();
       StringBuilder sb = new StringBuilder("[");
       sb.append(head.data);
       m.put(head, 0);
       int n = 1;
       for (IntNode p = head.next; p != null; p = p.next) {
           Integer boxed = m.get(p);
           if (boxed != null) {
               sb.append(", ..." + (n-boxed));
               break;
           }
           m.put(p, n++);
           sb.append(", " + p.data);
       }
       sb.append("]");
       return sb.toString();
   }  
   public static IntNode exercise0() {
       return null; // []
   }
  
   public static IntNode exercise1() {
       return null; // TODO [42], retrun list with single value in it. Number 42
   }
  
   public static IntNode exercise2() {
       return null; // TODO [1, 2, 3], return a list with the values 1,2, and 3. This will have 3 nodes
   }
  
   public static IntNode exercise3() {
       return null; // TODO [9, ...1], create a cyclic list of nines with a single node pointing to itself.
   }
  
   public static IntNode exercise4() {
       return null; // TODO [4, 3, 2, 1, ...3], create a list that starts 4, 3, 2, 1 but then cycles back to the "2"node again making a loop.
   }
  
   public static IntNode exercise5(IntNode param) {
       return null; // TODO: change second element to 4, change data in the second element of a list with at least two elements to "4"
   }
  
   public static IntNode exercise6(IntNode param) {
       return null; // TODO: remove second element, code should now remove(bypass) the second element of a list with at least two // elements
   }
  
   public static int exercise7(IntNode param) {
       return 0; // TODO: count number of nodes in list (use NORMAL loop), count up all nodes in the list passed in and rettrun the // count.
   }
  
   public static IntNode exercise8(IntNode param) {
       final IntNode dummy = new IntNode(999,null);
       IntNode last = dummy; // "last" node currently is the fake node.
      // TODO copy list by tacking on each element to the last node
       // of the result list. Use the NORMAL idiom

       return dummy.next;
   }
  
   public static IntNode exercise9(IntNode param, int v) {
       return null; // TODO: add v to the end of a non-empty list (in general!)
       // NB: We recommend using the FOLLOWER idiom

   }
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1
import java.util.IdentityHashMap;

public class IntNode implements Cloneable {
   private int data;
   private IntNode next;

   public IntNode(int d, IntNode n) {
       data = d;
       next = n;
   }

   public IntNode getNext() {
       return next;
   }


   /// Override methods from Object

   @Override
   public boolean equals(Object obj) {
       throw new UnsupportedOperationException("Don't use .equals to compare nodes!");
   }

   @Override
   public IntNode clone() {
       try {
           return (IntNode)super.clone();
       } catch (CloneNotSupportedException e) {
           throw new AssertionError("IntNodes should be cloneable!");
       }
   }

   protected String originalToString() {
       return super.toString();
   }

   @Override
   public String toString() {
       String nextString = "null";
       if (next != null) nextString = next.originalToString();
       return super.toString() + "(" + data + "." + nextString + ")";
   }


   /// Print method that is used for testing
   /**
   * Convert a list to a string for debugging purposes.
   * The string is of the form [n1, n2, n3, ...].
   * if the list ends in a cycle then we have "..." followed by
   * the one-based index of the node we go back to.
   * @param head list t print, may be null
   * @return string representation of the whole list.
   */
   public static String listToString(IntNode head) {
       if (head == null) return "[]";
       IdentityHashMap<IntNode,Integer> m = new IdentityHashMap<>();
       StringBuilder sb = new StringBuilder("[");
       sb.append(head.data);
       m.put(head, 0);
       int n = 1;
       for (IntNode p = head.next; p != null; p = p.next) {
           Integer boxed = m.get(p);
           if (boxed != null) {
               sb.append(", ..." + (n-boxed));
               break;
           }
           m.put(p, n++);
           sb.append(", " + p.data);
       }
       sb.append("]");
       return sb.toString();
   }  
   public static IntNode exercise0() {
       return null; // []
   }

   public static IntNode exercise1() {
       IntNode x = new IntNode(42, null);
       return x; // TODO [42], retrun list with single value in it. Number 42
   }

   public static IntNode exercise2() {
       IntNode x = new IntNode(1, new IntNode(2, new IntNode(3, null)));
       return x; // TODO [1, 2, 3], return a list with the values 1,2, and 3. This will have 3 nodes
   }

   public static IntNode exercise3() {
       IntNode x = null;
       for(int i=1; i<=9; i++) {
           x = new IntNode(i, x);
       }
       return x; // TODO [9, ...1], create a cyclic list of nines with a single node pointing to itself.
   }

   public static IntNode exercise4() {
       IntNode one = new IntNode(1, null);
       IntNode two = new IntNode(2, one);
       one.next = two;

       IntNode x = new IntNode(4, new IntNode(3, two));
       return x; // TODO [4, 3, 2, 1, ...3], create a list that starts 4, 3, 2, 1 but then cycles back to the "2"node again making a loop.
   }

   public static IntNode exercise5(IntNode param) {
       IntNode first = param.getNext();
       IntNode s = first.getNext();
       s.data = 4;
       return param; // TODO: change second element to 4, change data in the second element of a list with at least two elements to "4"
   }

   public static IntNode exercise6(IntNode param) {
       IntNode first = param.getNext();
       IntNode s = first.getNext();
       first.next = s.next;
       return param; // TODO: remove second element, code should now remove(bypass) the second element of a list with at least two // elements
   }

   public static int exercise7(IntNode param) {
       int count = 0;
       while(param != null) {
           count++;
           param = param.getNext();
       }
       return count; // TODO: count number of nodes in list (use NORMAL loop), count up all nodes in the list passed in and rettrun the // count.
   }

   public static IntNode exercise8(IntNode param) {
       final IntNode dummy = new IntNode(999,null);
       IntNode last = dummy; // "last" node currently is the fake node.
       // TODO copy list by tacking on each element to the last node
       // of the result list. Use the NORMAL idiom
       while(param != null) {
           last = new IntNode(param.data, last);
           param = param.next;
       }
       return dummy.next;
   }

   public static IntNode exercise9(IntNode param, int v) {
       if(param == null) {
           return new IntNode(v, null);
       }
       IntNode last = param;
       while(last.getNext() != null) {
           last = last.getNext();
       }
       last.next = new IntNode(v, null);

       return param; // TODO: add v to the end of a non-empty list (in general!)
       // NB: We recommend using the FOLLOWER idiom
   }
}
Add a comment
Know the answer?
Add Answer to:
Java/LinkedList Need help with a few of the TODO parts, more info below in comments in...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I need help with todo line please public class LinkedList { private Node head; public LinkedList()...

    I need help with todo line please public class LinkedList { private Node head; public LinkedList() { head = null; } public boolean isEmpty() { return head == null; } public int size() { int count = 0; Node current = head; while (current != null) { count++; current = current.getNext(); } return count; } public void add(int data) { Node newNode = new Node(data); newNode.setNext(head); head = newNode; } public void append(int data) { Node newNode = new Node(data);...

  • Data Structures - Singly Linked Lists You will add a method swapNodes to SinglyLinkedList class (below). This method should swap two nodes node1 and node2 (and not just their contents) given reference...

    Data Structures - Singly Linked Lists You will add a method swapNodes to SinglyLinkedList class (below). This method should swap two nodes node1 and node2 (and not just their contents) given references only to node1 and node2. The new method should check if node1 and node2 are the same node, etc. Write the main method to test the swapNodes method. You may need to traverse the list. package linkedlists; public class SinglyLinkedList<E> implements Cloneable {    // ---------------- nested Node class...

  • In Java Language. Modify the LinkedPostionalList class to support a method swap(p,q) that causes the underlying...

    In Java Language. Modify the LinkedPostionalList class to support a method swap(p,q) that causes the underlying nodes referenced by positions p and q to be exchanged for each other. Relink the existing nodes, do not create any new nodes. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- package lists; import java.util.Iterator; import java.util.NoSuchElementException; public class LinkedPositionalList implements PositionalList { //---------------- nested Node class ---------------- /** * Node of a doubly linked list, which stores a reference to its * element and to both the previous and next...

  • n JAVA, students will create a linked list structure that will be used to support a...

    n JAVA, students will create a linked list structure that will be used to support a role playing game. The linked list will represent the main character inventory. The setting is a main character archeologist that is traveling around the jungle in search of an ancient tomb. The user can add items in inventory by priority as they travel around (pickup, buy, find), drop items when their bag is full, and use items (eat, spend, use), view their inventory as...

  • JAVA: Already completed: MyList.java, MyAbstractList.java, MyArrayList.java, MyLinkedLink.java, MyStack.java, MyQueue.java. Need to complete: ReversePoem.java. This program has...

    JAVA: Already completed: MyList.java, MyAbstractList.java, MyArrayList.java, MyLinkedLink.java, MyStack.java, MyQueue.java. Need to complete: ReversePoem.java. This program has you display a pessimistic poem from a list of phrases. Next, this program has you reverse the phrases to find another more optimistic poem. Use the following algorithm. 1.   You are given a list of phrases each ending with a pound sign: ‘#’. 2.   Create a single String object from this list. 3.   Then, split the String of phrases into an array of phrases...

  • Java: Return an array of booleans in a directed graph. Please complete the TODO section in...

    Java: Return an array of booleans in a directed graph. Please complete the TODO section in the mark(int s) function import algs13.Bag; import java.util.HashSet; // See instructions below public class MyDigraph { static class Node { private String key; private Bag<Node> adj; public Node (String key) { this.key = key; this.adj = new Bag<> (); } public String toString () { return key; } public void addEdgeTo (Node n) { adj.add (n); } public Bag<Node> adj () { return adj;...

  • LAB: Inserting an integer in descending order (doubly-linked list) Given main() and an IntNode class, complete...

    LAB: Inserting an integer in descending order (doubly-linked list) Given main() and an IntNode class, complete the IntList class (a linked list of IntNodes) by writing the insertInDescendingOrder() method to insert new IntNodes into the IntList in descending order. Ex. If the input is: 3 4 2 5 1 6 7 9 8 -1 the output is: 9 8 7 6 5 4 3 2 1 ___________________________________________________________________________________________________________________________________________________ SortedList.java (READ ONLY!!!) import java.util.Scanner; public class SortedList { public static void main...

  • Java help! Please help complete the min method below in bold. import java.util.Arrays; import java.util.ArrayList; import...

    Java help! Please help complete the min method below in bold. import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * Provides an implementation of a binary search tree * with no balance constraints, implemented with linked nodes. * * * */ public class Bst<T extends Comparable<T>> implements Iterable<T> { ////////////////////////////////////////////////////////////////// // I M P L E M E N T T H E M I N M E T H O D B E L O W...

  • In Java You may add any classes or methods to the following as you see fit in order to complete t...

    In Java You may add any classes or methods to the following as you see fit in order to complete the given tasks. Modify the LinkedList (or DoubleLinkedList) class and add a method append. append should take another LinkedList (DoubleLinkedList) as input and append that list to the end of this list. The append method should work by doing a few "arrow" adjustments on the boxes and it should not loop through the input list to add elements one at...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT