Question

Complete P16.1 and P16.4 (Class Name: NewMethodDemo) Once complete, upload all .java files. For primary test...

Complete P16.1 and P16.4 (Class Name: NewMethodDemo)

Once complete, upload all .java files.

For primary test class: Remember your header with name, date, and assignment. Also include class names that will be tested. Psuedocode (level 0 or mixture of level 0 and algorithm [do not number steps]) is required if main() contains more than simple statements (for example, your program includes constructs for decisions (if/else), loops, and methods.

For Secondary class(es): Include a JavaDoc comment that describes the purpose of the class definition at the top of the file.

Block level comments are required. You should comment anytime coding is not clear. That is just good programming.

Question

P16.1
Add a method reverse to our implementation of the LinkedList class that reverses the links in a list. Implement this method by directly rerouting the links, not by using an iterator.

P16.4
Add a method size to our implementation of the LinkedList class that computes the number of elements in the list by following links and counting the elements until the end of the list is reached.

LinkedList Class

import java.util.NoSuchElementException;

/**
A linked list is a sequence of nodes with efficient
element insertion and removal. This class
contains a subset of the methods of the standard
java.util.LinkedList class.
*/
public class LinkedList
{  
private Node first;

/**
Constructs an empty linked list.
*/
public LinkedList()
{  
first = null;
}

/**
Returns the first element in the linked list.
@return the first element in the linked list
*/
public Object getFirst()
{  
if (first == null) { throw new NoSuchElementException(); }
return first.data;
}

/**
Removes the first element in the linked list.
@return the removed element
*/
public Object removeFirst()
{  
if (first == null) { throw new NoSuchElementException(); }
Object element = first.data;
first = first.next;
return element;
}

/**
Adds an element to the front of the linked list.
@param element the element to add
*/
public void addFirst(Object element)
{  
Node newNode = new Node();
newNode.data = element;
newNode.next = first;
first = newNode;
}

/**
Returns an iterator for iterating through this list.
@return an iterator for iterating through this list
*/
public ListIterator listIterator()
{  
return new LinkedListIterator();
}

class Node
{  
public Object data;
public Node next;
}

class LinkedListIterator implements ListIterator
{  
private Node position;
private Node previous;
private boolean isAfterNext;

/**
Constructs an iterator that points to the front
of the linked list.
*/
public LinkedListIterator()
{  
position = null;
previous = null;
isAfterNext = false;
}
  
/**
Moves the iterator past the next element.
@return the traversed element
*/
public Object next()
{  
if (!hasNext()) { throw new NoSuchElementException(); }
previous = position; // Remember for remove
isAfterNext = true;

if (position == null)
{
position = first;
}
else
{
position = position.next;
}

return position.data;
}
  
/**
Tests if there is an element after the iterator position.
@return true if there is an element after the iterator position
*/
public boolean hasNext()
{  
if (position == null)
{
return first != null;
}
else
{
return position.next != null;
}
}
  
/**
Adds an element before the iterator position
and moves the iterator past the inserted element.
@param element the element to add
*/
public void add(Object element)
{  
if (position == null)
{
addFirst(element);
position = first;
}
else
{  
Node newNode = new Node();
newNode.data = element;
newNode.next = position.next;
position.next = newNode;
position = newNode;
}

isAfterNext = false;
}
  
/**
Removes the last traversed element. This method may
only be called after a call to the next() method.
*/
public void remove()
{  
if (!isAfterNext) { throw new IllegalStateException(); }

if (position == first)
{
removeFirst();
}
else
{  
previous.next = position.next;
}
position = previous;
isAfterNext = false;
}

/**
Sets the last traversed element to a different value.
@param element the element to set
*/
public void set(Object element)
{
if (!isAfterNext) { throw new IllegalStateException(); }
position.data = element;
}
}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

import java.util.NoSuchElementException;

/**

A linked list is a sequence of nodes with efficient

element insertion and removal. This class

contains a subset of the methods of the standard

java.util.LinkedList class.

*/

public class LinkedList

{

private Node first;

/**

Constructs an empty linked list.

*/

public LinkedList()

{

first = null;

}

/**

Returns the first element in the linked list.

@return the first element in the linked list

*/

public Object getFirst()

{

if (first == null) { throw new NoSuchElementException(); }

return first.data;

}

/**

Removes the first element in the linked list.

@return the removed element

*/

public Object removeFirst()

{

if (first == null) { throw new NoSuchElementException(); }

Object element = first.data;

first = first.next;

return element;

}

/**

Adds an element to the front of the linked list.

@param element the element to add

*/

public void addFirst(Object element)

{

Node newNode = new Node();

newNode.data = element;

newNode.next = first;

first = newNode;

}

/*

P16.4 : Returns the size of the linked list

*/

public int size()

{

               int count = 0;

               Node current = first;

               while(current != null)

               {

                              count++;

                              current = current.next;

               }

               return count;    

}

/*

P16.1 : Reverse the linked list by directly rerouting the links

*/

public void reverse()

{

               Node current = first; //set current node to first

               Node prev = null; // prev = null

               Node next = null; // next = null

               // loop that continues till all the links have been changed

               while(current != null)

               {

                              next = current.next; // get the node which next of current

                              current.next = prev; // set next of current to previous node

                              prev = current; // set previous to current

                              current = next; // current will be the previous next of current

               }

               first = prev; // finally set first node to previous last node

}

/**

Returns an iterator for iterating through this list.

@return an iterator for iterating through this list

*/

public ListIterator listIterator()

{

return new LinkedListIterator();

}

class Node

{

public Object data;

public Node next;

}

class LinkedListIterator implements ListIterator

{

private Node position;

private Node previous;

private boolean isAfterNext;

/**

Constructs an iterator that points to the front

of the linked list.

*/

public LinkedListIterator()

{

position = null;

previous = null;

isAfterNext = false;

}

/**

Moves the iterator past the next element.

@return the traversed element

*/

public Object next()

{

if (!hasNext()) { throw new NoSuchElementException(); }

previous = position; // Remember for remove

isAfterNext = true;

if (position == null)

{

position = first;

}

else

{

position = position.next;

}

return position.data;

}

/**

Tests if there is an element after the iterator position.

@return true if there is an element after the iterator position

*/

public boolean hasNext()

{

if (position == null)

{

return first != null;

}

else

{

return position.next != null;

}

}

/**

Adds an element before the iterator position

and moves the iterator past the inserted element.

@param element the element to add

*/

public void add(Object element)

{

if (position == null)

{

addFirst(element);

position = first;

}

else

{

Node newNode = new Node();

newNode.data = element;

newNode.next = position.next;

position.next = newNode;

position = newNode;

}

isAfterNext = false;

}

/**

Removes the last traversed element. This method may

only be called after a call to the next() method.

*/

public void remove()

{

if (!isAfterNext) { throw new IllegalStateException(); }

if (position == first)

{

removeFirst();

}

else

{

previous.next = position.next;

}

position = previous;

isAfterNext = false;

}

/**

Sets the last traversed element to a different value.

@param element the element to set

*/

public void set(Object element)

{

if (!isAfterNext) { throw new IllegalStateException(); }

position.data = element;

}

}

}

Add a comment
Know the answer?
Add Answer to:
Complete P16.1 and P16.4 (Class Name: NewMethodDemo) Once complete, upload all .java files. For primary test...
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
  • 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...

  • Please help with the codes for the implementation of java.util.List, specifically for the 3 below overridden...

    Please help with the codes for the implementation of java.util.List, specifically for the 3 below overridden methods @Override        public int lastIndexOf(Object arg0) { required code }        @Override        public ListIterator<R> listIterator() { required code }        @Override        public ListIterator<R> listIterator(int arg0) { required code } PLEASE NOTE: Below are some of other overridden methods that are already implemented, they are meant to be examples of what the answers to the above questions for the 3 methods should...

  • Java help: Please help complete the locate method that is in bold.. public class LinkedDoubleEndedList implements...

    Java help: Please help complete the locate method that is in bold.. public class LinkedDoubleEndedList implements DoubleEndedList { private Node front; // first node in list private Node rear; // last node in list private int size; // number of elements in list ////////////////////////////////////////////////// // YOU MUST IMPLEMENT THE LOCATE METHOD BELOW // ////////////////////////////////////////////////// /** * Returns the position of the node containing the given value, where * the front node is at position zero and the rear node is...

  • //LinkedList import java.util.Scanner; public class PoD {    public static void main( String [] args )...

    //LinkedList import java.util.Scanner; public class PoD {    public static void main( String [] args ) { Scanner in = new Scanner( System.in ); LinkedList teamList = new LinkedList(); final int TEAM_SIZE = Integer.valueOf(in.nextLine()); for (int i=0; i<TEAM_SIZE; i++) { String newTeamMember = in.nextLine(); teamList.append(newTeamMember); } while (in.hasNext()) { String removeMember = in.nextLine(); teamList.remove(removeMember); }    System.out.println("FINAL TEAM:"); System.out.println(teamList); in.close(); System.out.print("END OF OUTPUT"); } } =========================================================================================== //PoD import java.util.NoSuchElementException; /** * A listnked list is a sequence of nodes with...

  • When compiling the LinkedList and Iterator class, the following error is being produced: Note: LinkedList.java uses...

    When compiling the LinkedList and Iterator class, the following error is being produced: Note: LinkedList.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. Any suggestions? public class LinkedList<T> {    Node<T> itsFirstNode;    Node<T> itsLastNode;    private int size;    public LinkedList() {        itsFirstNode = null;        itsLastNode = null;          size = 0;    }    public Iterator<T> getIterator() {        return new Iterator(this);    }    // THIS WILL NEED...

  • This Individual Assignment is a set of three problems. The first is a recursion "warm up"...

    This Individual Assignment is a set of three problems. The first is a recursion "warm up" exercise, and the second two are QuickSort variations. The "warm up" should be implemented as a static method in your main App class and the second two will use additional classes (as instructed below). All three problems should be included in the same NetBeans project (exported to ZIP as usual). ----------------- All of your classes should be properly encapsulated, follow all proper coding conventions...

  • 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...

  • Below is the given code of implementation: #include <string> #include <iostream> #include <list> #include <cassert> using...

    Below is the given code of implementation: #include <string> #include <iostream> #include <list> #include <cassert> using namespace std; class List; class Iterator; class Node { public: /* Constructs a node with a given data value. @param s the data to store in this node */ Node(string s); /* Destructor */ ~Node() {} private: string data; Node* previous; Node* next; friend class List; friend class Iterator; }; class List { public: /** Constructs an empty list. */ List(); /* Destructor. Deletes...

  • Draw a sketch to illustrate the steps (as it appears in the code) of adding the...

    Draw a sketch to illustrate the steps (as it appears in the code) of adding the new node 6 to MyNumbers using the following code. Note: you must show node structure, ListIterator and all the references public void add(Object obj) {    if (position == null)    {       addFirst(obj);       position = first;    }    else    {       Node newNode = new Node();       newNode.data = obj;       newNode.next = position.next; // step 1         position.next =...

  • Java StringNode Case Study: Rewrite the following methods in the StringNode class shown below. Leave all...

    Java StringNode Case Study: Rewrite the following methods in the StringNode class shown below. Leave all others intact and follow similar guidelines. The methods that need to be changed are in the code below. - Rewrite the indexOf() method. Remove the existing recursive implementation of the method, and replace it with one that uses iteration instead. - Rewrite the isPrefix() method so that it uses iteration. Remove the existing recursive implementation of the method, and replace it with one that...

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