Currently working on a Java Assignment. I have written most codes for swap, reverse and insert.
Just need
a. itemCount
receives a value and returns a count of the number of times this item
is found in the list.
c. sublist
receives two indexes and returns an ArrayList of node values from the first
index to the second index, provided the indexes are valid.
d. select
receives a variable number of indexes, and returns an ArrayList of node values
corresponding to each index given, provided the indexes are valid.
attaching my code below:
import org.omg.CORBA.Any;
/**
* LinkedList class implements a doubly-linked list.
*/
public class MyLinkedList<AnyType> implements Iterable<AnyType>
{
/**
* Construct an empty LinkedList
*/
public MyLinkedList( )
{
doClear( );
}
private void clear( )
{
doClear( );
}
/**
* Change the size of this collection to zero.
*/
public void doClear( )
{
beginMarker = new Node<>( null, null, null );
endMarker = new Node<>( null, beginMarker, null );
beginMarker.next = endMarker;
theSize = 0;
modCount++;
}
/**
* Returns the number of items in this collection.
* @return the number of items in this collection.
*/
public int size( )
{
return theSize;
}
public boolean isEmpty( )
{
return size( ) == 0;
}
/**
* Adds an item to this collection, at the end.
* @param x any object.
* @return true.
*/
public boolean add( AnyType x )
{
add( size( ), x );
return true;
}
/**
* Adds an item to this collection, at specified position.
* Items at or after that position are slid one position higher.
* @param x any object.
* @param idx position to add at.
* @throws IndexOutOfBoundsException if idx is not between 0 and size(), inclusive.
*/
public void add( int idx, AnyType x )
{
addBefore( getNode( idx, 0, size( ) ), x );
}
/**
* Adds an item to this collection, at specified position p.
* Items at or after that position are slid one position higher.
* @param p Node to add before.
* @param x any object.
* @throws IndexOutOfBoundsException if idx is not between 0 and size(), inclusive.
*/
private void addBefore( Node<AnyType> p, AnyType x )
{
Node<AnyType> newNode = new Node<>( x, p.prev, p );
newNode.prev.next = newNode;
p.prev = newNode;
theSize++;
modCount++;
}
/**
* Returns the item at position idx.
* @param idx the index to search in.
* @throws IndexOutOfBoundsException if index is out of range.
*/
public AnyType get( int idx )
{
return getNode( idx ).data;
}
/** ADDED REVERSE--------------------------------*/
public void reverse()
{ if (theSize <2)
return;
Node <AnyType> p1,p2,p3;
p1 = null;
p2 = beginMarker;
p3 = beginMarker.next;
while (p3 != null)
{
p2.next = p1;
p1 = p2;
p2 = p3;
p3 = p3.next;
}
p2.next = p1;
endMarker = beginMarker;
beginMarker = p2;
{}
}
/**
* Changes the item at position idx.
* @param idx the index to change.
* @param newVal the new value.
* @return the old value.
* @throws IndexOutOfBoundsException if index is out of range.
*/
public AnyType set( int idx, AnyType newVal )
{
Node<AnyType> p = getNode( idx );
AnyType oldVal = p.data;
p.data = newVal;
return oldVal;
}
/**
* Gets the Node at position idx, which must range from 0 to size( ) - 1.
* @param idx index to search at.
* @return internal node corresponding to idx.
* @throws IndexOutOfBoundsException if idx is not between 0 and size( ) - 1, inclusive.
*/
private Node<AnyType> getNode( int idx )
{
return getNode( idx, 0, size( ) - 1 );
}
/**
* Gets the Node at position idx, which must range from lower to upper.
* @param idx index to search at.
* @param lower lowest valid index.
* @param upper highest valid index.
* @return internal node corresponding to idx.
* @throws IndexOutOfBoundsException if idx is not between lower and upper, inclusive.
*/
private Node<AnyType> getNode( int idx, int lower, int upper )
{
Node<AnyType> p;
if( idx < lower || idx > upper )
throw new IndexOutOfBoundsException( "getNode index: " + idx + "; size: " + size( ) );
if( idx < size( ) / 2 )
{
p = beginMarker.next;
for( int i = 0; i < idx; i++ )
p = p.next;
}
else
{
p = endMarker;
for( int i = size( ); i > idx; i-- )
p = p.prev;
}
return p;
}
/**
* Removes an item from this collection.
* @param idx the index of the object.
* @return the item was removed from the collection.
*/
public AnyType remove( int idx )
{
return remove( getNode( idx ) );
}
/**
* Removes the object contained in Node p.
* @param p the Node containing the object.
* @return the item was removed from the collection.
*/
private AnyType remove( Node<AnyType> p )
{
p.next.prev = p.prev;
p.prev.next = p.next;
theSize--;
modCount++;
return p.data;
}
/**
* Returns a String representation of this collection.
*/
public String toString( )
{
StringBuilder sb = new StringBuilder( "[ " );
for( AnyType x : this )
sb.append( x + " " );
sb.append( "]" );
return new String( sb );
}
/**
* Obtains an Iterator object used to traverse the collection.
* @return an iterator positioned prior to the first element.
*/
public java.util.Iterator<AnyType> iterator( )
{
return new LinkedListIterator( );
}
/**
* This is the implementation of the LinkedListIterator.
* It maintains a notion of a current position and of
* course the implicit reference to the MyLinkedList.
*/
private class LinkedListIterator implements java.util.Iterator<AnyType>
{
private Node<AnyType> current = beginMarker.next;
private int expectedModCount = modCount;
private boolean okToRemove = false;
public boolean hasNext( )
{
return current != endMarker;
}
public AnyType next( )
{
if( modCount != expectedModCount )
throw new java.util.ConcurrentModificationException( );
if( !hasNext( ) )
throw new java.util.NoSuchElementException( );
AnyType nextItem = current.data;
current = current.next;
okToRemove = true;
return nextItem;
}
public void remove( )
{
if( modCount != expectedModCount )
throw new java.util.ConcurrentModificationException( );
if( !okToRemove )
throw new IllegalStateException( );
MyLinkedList.this.remove( current.prev );
expectedModCount++;
okToRemove = false;
}
}
/**
* This is the doubly-linked list node.
*/
private static class Node<AnyType>
{
public Node( AnyType d, Node<AnyType> p, Node<AnyType> n )
{
data = d; prev = p; next = n;
}
public AnyType data;
public Node<AnyType> prev;
public Node<AnyType> next;
}
private int theSize;
private int modCount = 0;
private Node<AnyType> beginMarker;
private Node<AnyType> endMarker;
// swap method implementation
public void swap(int pos1, int pos2)
{
if((pos1 < 0 || pos1 >= size()) || (pos2 < 0 || pos2 >= size()))
throw new IndexOutOfBoundsException();
Node<AnyType> node1 = getNode(pos1);
Node<AnyType> node2 = getNode(pos2);
Node<AnyType> temp1 = node1.prev;
Node<AnyType> temp2 = node1.next;
Node<AnyType> temp3 = node2.prev;
Node<AnyType> temp4 = node2.next;
if(temp1!= null)
temp1.next = node2;
node2.prev = temp1;
if(temp2 != null)
temp2.prev = node2;
node2.next = temp2;
if(temp3!= null)
temp3.next = node1;
node1.prev = temp3;
if(temp4 != null)
temp4.prev = node1;
node1.next = temp4;
} // end of swap method
// erase method implementation
public void erase(int pos, int n)
{
if(n == 0)
return;
if(pos < 0 || pos >= size() || pos + n > size())
throw new IndexOutOfBoundsException();
Node<AnyType> currentNode = getNode(pos).prev;
Node<AnyType> nextNode = currentNode;
int count = 0;
while(count <= n)
{
nextNode = nextNode.next;
count++;
}
currentNode.next = nextNode;
if(nextNode != null)
nextNode.prev = currentNode;
theSize -= n;
} // end of erase method
// insertList method implementation
public void insertList(MyLinkedList<AnyType> list, int pos)
{
if(pos < 0 || pos >= size())
throw new IndexOutOfBoundsException();
for(int i = 0; i < list.size(); i++)
{
add(pos, list.get(i));
pos++;
}
} // end of insertList method
public void shift(int s) {
Node<AnyType> p = beginMarker.next;
Node<AnyType> q = endMarker.prev;
// make circular
q.next = p;
p.prev = q;
// shift
if (s > 0) {
for (int i = 0; i < s; i++) {
p = p.next;
q = q.next;
}
} else {
for (int i = 0; i > s; i--) {
p = p.prev;
q = q.prev;
}
}
beginMarker.next = p;
p.prev = beginMarker;
endMarker.prev = q;
q.next = endMarker;
}
}
class TestLinkedList
{
public static void main( String [ ] args )
{
MyLinkedList<Integer> lst = new MyLinkedList<>( );
for( int i = 0; i < 10; i++ )
lst.add( i );
for( int i = 20; i < 30; i++ )
lst.add( 0, i );
/*
ADDED BY TEST FOR REVERSE
*/
System.out.println(lst);
lst.reverse();
System.out.println(lst);
lst.reverse();
//System.out.println(lst);
//lst.remove(0);
//lst.remove(lst.size() -1);
System.out.println(lst);
System.out.println("\nTOriginal List: ");
java.util.Iterator<Integer> itr = lst.iterator();
while(itr.hasNext())
System.out.print(itr.next() + " ");
System.out.println();
System.out.println("Original List");
System.out.println("\nBefore Swap method: ");
System.out.println(lst);
lst.swap(0, lst.size() - 1);
System.out.println("\nAfter swap method: ");
System.out.println(lst);
lst.erase(0, 3);
System.out.println("\nBefore erase method: ");
System.out.println(lst);
System.out.println("\nShifting");
System.out.println(lst);
System.out.println("\n After Shifting:");
System.out.println(lst);
lst.shift(2);
System.out.println( lst );
lst.shift(-1);
MyLinkedList<Integer> list2 = new MyLinkedList<Integer>();
list2.add(11);
list2.add(22);
list2.add(33);
System.out.println("\n insertList:");
System.out.println(list2);
lst.insertList(list2, 2);
System.out.println("\nCalling the insertList method: ");
System.out.println(lst);
//java.util.Iterator<Integer> itr = lst.iterator( );
//while( itr.hasNext( ) )
{
// itr.next( );
// itr.remove( );
// System.out.println( lst );
}
}
}Here is the completed code for this problem. Just added the three required methods. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
// MyLinkedList.java
import java.util.ArrayList;
/**
* LinkedList class implements a doubly-linked list.
*/
public class MyLinkedList<AnyType> implements Iterable<AnyType> {
/**
* Construct an empty LinkedList
*/
public MyLinkedList() {
doClear();
}
private void clear() {
doClear();
}
/**
* Change the size of this collection to zero.
*/
public void doClear() {
beginMarker = new Node<AnyType>(null, null, null);
endMarker = new Node<AnyType>(null, beginMarker, null);
beginMarker.next = endMarker;
theSize = 0;
modCount++;
}
/**
* Returns the number of items in this collection.
*
* @return the number of items in this collection.
*/
public int size() {
return theSize;
}
public boolean isEmpty() {
return size() == 0;
}
/**
* Adds an item to this collection, at the end.
*
* @param x
* any object.
* @return true.
*/
public boolean add(AnyType x) {
add(size(), x);
return true;
}
/**
* Adds an item to this collection, at specified position. Items at or after
* that position are slid one position higher.
*
* @param x
* any object.
* @param idx
* position to add at.
* @throws IndexOutOfBoundsException
* if idx is not between 0 and size(), inclusive.
*/
public void add(int idx, AnyType x) {
addBefore(getNode(idx, 0, size()), x);
}
/**
* Adds an item to this collection, at specified position p. Items at or
* after that position are slid one position higher.
*
* @param p
* Node to add before.
* @param x
* any object.
* @throws IndexOutOfBoundsException
* if idx is not between 0 and size(), inclusive.
*/
private void addBefore(Node<AnyType> p, AnyType x) {
Node<AnyType> newNode = new Node<AnyType>(x, p.prev, p);
newNode.prev.next = newNode;
p.prev = newNode;
theSize++;
modCount++;
}
/**
* Returns the item at position idx.
*
* @param idx
* the index to search in.
* @throws IndexOutOfBoundsException
* if index is out of range.
*/
public AnyType get(int idx) {
return getNode(idx).data;
}
/** ADDED REVERSE-------------------------------- */
public void reverse() {
if (theSize < 2)
return;
Node<AnyType> p1, p2, p3;
p1 = null;
p2 = beginMarker;
p3 = beginMarker.next;
while (p3 != null) {
p2.next = p1;
p1 = p2;
p2 = p3;
p3 = p3.next;
}
p2.next = p1;
endMarker = beginMarker;
beginMarker = p2;
{
}
}
/**
* Changes the item at position idx.
*
* @param idx
* the index to change.
* @param newVal
* the new value.
* @return the old value.
* @throws IndexOutOfBoundsException
* if index is out of range.
*/
public AnyType set(int idx, AnyType newVal) {
Node<AnyType> p = getNode(idx);
AnyType oldVal = p.data;
p.data = newVal;
return oldVal;
}
/**
* Gets the Node at position idx, which must range from 0 to size( ) - 1.
*
* @param idx
* index to search at.
* @return internal node corresponding to idx.
* @throws IndexOutOfBoundsException
* if idx is not between 0 and size( ) - 1, inclusive.
*/
private Node<AnyType> getNode(int idx) {
return getNode(idx, 0, size() - 1);
}
/**
* Gets the Node at position idx, which must range from lower to upper.
*
* @param idx
* index to search at.
* @param lower
* lowest valid index.
* @param upper
* highest valid index.
* @return internal node corresponding to idx.
* @throws IndexOutOfBoundsException
* if idx is not between lower and upper, inclusive.
*/
private Node<AnyType> getNode(int idx, int lower, int upper) {
Node<AnyType> p;
if (idx < lower || idx > upper)
throw new IndexOutOfBoundsException("getNode index: " + idx
+ "; size: " + size());
if (idx < size() / 2) {
p = beginMarker.next;
for (int i = 0; i < idx; i++)
p = p.next;
} else {
p = endMarker;
for (int i = size(); i > idx; i--)
p = p.prev;
}
return p;
}
/**
* Removes an item from this collection.
*
* @param idx
* the index of the object.
* @return the item was removed from the collection.
*/
public AnyType remove(int idx) {
return remove(getNode(idx));
}
/**
* Removes the object contained in Node p.
*
* @param p
* the Node containing the object.
* @return the item was removed from the collection.
*/
private AnyType remove(Node<AnyType> p) {
p.next.prev = p.prev;
p.prev.next = p.next;
theSize--;
modCount++;
return p.data;
}
/**
* Returns a String representation of this collection.
*/
public String toString() {
StringBuilder sb = new StringBuilder("[ ");
for (AnyType x : this)
sb.append(x + " ");
sb.append("]");
return new String(sb);
}
/**
* Obtains an Iterator object used to traverse the collection.
*
* @return an iterator positioned prior to the first element.
*/
public java.util.Iterator<AnyType> iterator() {
return new LinkedListIterator();
}
/**
* This is the implementation of the LinkedListIterator. It maintains a
* notion of a current position and of course the implicit reference to the
* MyLinkedList.
*/
private class LinkedListIterator implements java.util.Iterator<AnyType> {
private Node<AnyType> current = beginMarker.next;
private int expectedModCount = modCount;
private boolean okToRemove = false;
public boolean hasNext() {
return current != endMarker;
}
public AnyType next() {
if (modCount != expectedModCount)
throw new java.util.ConcurrentModificationException();
if (!hasNext())
throw new java.util.NoSuchElementException();
AnyType nextItem = current.data;
current = current.next;
okToRemove = true;
return nextItem;
}
public void remove() {
if (modCount != expectedModCount)
throw new java.util.ConcurrentModificationException();
if (!okToRemove)
throw new IllegalStateException();
MyLinkedList.this.remove(current.prev);
expectedModCount++;
okToRemove = false;
}
}
/**
* This is the doubly-linked list node.
*/
private static class Node<AnyType> {
public Node(AnyType d, Node<AnyType> p, Node<AnyType> n) {
data = d;
prev = p;
next = n;
}
public AnyType data;
public Node<AnyType> prev;
public Node<AnyType> next;
}
private int theSize;
private int modCount = 0;
private Node<AnyType> beginMarker;
private Node<AnyType> endMarker;
// swap method implementation
public void swap(int pos1, int pos2) {
if ((pos1 < 0 || pos1 >= size()) || (pos2 < 0 || pos2 >= size()))
throw new IndexOutOfBoundsException();
Node<AnyType> node1 = getNode(pos1);
Node<AnyType> node2 = getNode(pos2);
Node<AnyType> temp1 = node1.prev;
Node<AnyType> temp2 = node1.next;
Node<AnyType> temp3 = node2.prev;
Node<AnyType> temp4 = node2.next;
if (temp1 != null)
temp1.next = node2;
node2.prev = temp1;
if (temp2 != null)
temp2.prev = node2;
node2.next = temp2;
if (temp3 != null)
temp3.next = node1;
node1.prev = temp3;
if (temp4 != null)
temp4.prev = node1;
node1.next = temp4;
} // end of swap method
// erase method implementation
public void erase(int pos, int n) {
if (n == 0)
return;
if (pos < 0 || pos >= size() || pos + n > size())
throw new IndexOutOfBoundsException();
Node<AnyType> currentNode = getNode(pos).prev;
Node<AnyType> nextNode = currentNode;
int count = 0;
while (count <= n) {
nextNode = nextNode.next;
count++;
}
currentNode.next = nextNode;
if (nextNode != null)
nextNode.prev = currentNode;
theSize -= n;
} // end of erase method
// insertList method implementation
public void insertList(MyLinkedList<AnyType> list, int pos) {
if (pos < 0 || pos >= size())
throw new IndexOutOfBoundsException();
for (int i = 0; i < list.size(); i++) {
add(pos, list.get(i));
pos++;
}
} // end of insertList method
public void shift(int s) {
Node<AnyType> p = beginMarker.next;
Node<AnyType> q = endMarker.prev;
// make circular
q.next = p;
p.prev = q;
// shift
if (s > 0) {
for (int i = 0; i < s; i++) {
p = p.next;
q = q.next;
}
} else {
for (int i = 0; i > s; i--) {
p = p.prev;
q = q.prev;
}
}
beginMarker.next = p;
p.prev = beginMarker;
endMarker.prev = q;
q.next = endMarker;
}
// given an item, returns the count of it in the linked list
public int itemCount(AnyType item) {
// initializing count to 0
int count = 0;
// looping through each node
for (int i = 0; i < size(); i++) {
// comparing value with current item
if (get(i).equals(item)) {
// same, incrementing count
count++;
}
}
return count;
}
// given start and end indices, returns the values between the nodes at
// those indices
ArrayList<AnyType> sublist(int start, int end) {
// returning null if either index is invalid
if (start < 0 || start >= size() || end < 0 || end >= size()
|| start > end) {
return null; // invalid indices
}
// creating an array list
ArrayList<AnyType> list = new ArrayList<AnyType>();
// looping from start to end
for (int i = start; i <= end; i++) {
// getting element at index i and adding to list
list.add(get(i));
}
return list;
}
// given a list of variable arguments containing indices, returns the
// elements corresponding to those indices
ArrayList<AnyType> select(int... indices) {
// creating a list
ArrayList<AnyType> list = new ArrayList<AnyType>();
// looping through the indices
for (int i = 0; i < indices.length; i++) {
int index = indices[i];
// if index is not valid, adding a null value to the list
if (index < 0 || index >= size()) {
list.add(null);
} else
// otherwise, adds the element at that index to the list
list.add(get(index));
}
return list;
}
}
Currently working on a Java Assignment. I have written most codes for swap, reverse and insert....
Java Programming: The following is my code: public class KWSingleLinkedList<E> { public void setSize(int size) { this.size = size; } /** Reference to list head. */ private Node<E> head = null; /** The number of items in the list */ private int size = 0; /** Add an item to the front of the list. @param item The item to be added */ public void addFirst(E...
Why is the answer 10 and 0 (respectively - two different answers, one is 10 and the second one is 0)? I don't know how to trace this. Please don't be too complex in your explanation. Consider the following class public class Node { private int item; private Node next; public Node() { this(0); } public Node(int item) { this(item, null); } public Node(int item, Node next) {...
Java Quadratic Probing Hash table HELP! Complete the Map and Entry class provided in Map.java. Create a tester/driver class to show the Map class is working as intended. Methods/Constructor correctly completed (2pt) This is the Map class methods Map(), put(key, value), get(key), isEmpty(), makeEmpty() Private class correctly completed (2pt) This is the Entry class methods Add the methods that are required for this to work correctly when stored in the QuadraticProbingHashTable Tester class (1pt) Show the methods of the Map...
could somone please help me to complete this ! public class MyLinkedList<AnyType> { private Node<AnyType> head, tail; private int size; public MyLinkedList() { this.head = null; this.tail = null; this.size = 0; } //1.Insert a node at the end of the list public void insert(AnyType data) { Node<AnyType> newNode = new Node(); newNode.data = data; if (head == null) { head = newNode; tail = newNode; head.next = null; tail.next = null; } else { tail.next = newNode; tail =...
Part I: Create a doubly linked circular list class named LinkedItemList that implements the following interface: /** * An ordered list of items. */ public interface ItemList<E> { /** * Append an item to the end of the list * * @param item – item to be appended */ public void append(E item); /** * Insert an item at a specified index position * * @param item – item to be...
Java - I need help creating a method that removes a node at the specific index position. The * first node is index 0. public boolean delAt(int index) { src code 2 different classes ******************************************** public class Node { private String data; private Node next; public Node(String data, Node next) { this.data = data; this.next = next; } public Node() { } public String getData() { return data; } public void setData(String data) { this.data = data; } public void...
-Fill in the reverse method below to return a new DoublyLinkedList consisting of the same elements in reverse order. -The reverse method must not modify the original DoublyLinkedList. -The reverse method must run in linear time. Can someone answer this for me, please? In Java public class DoublyLinkedList { int size; Node firstNode; Node lastNode; public DoublyLinkedList() { size = 0; firstNode = null; lastNode = null; } // Problem 1 (15 pts) // Fill in the method below to...
Problem 2: based on java.util.LinkedList class, create MyStack class that should have the methods: push(), pop(), peek(), size(), isEmpty(). my linkedlist class is: public class Lab8_problem1 { private Node head, tail; private int size; public Lab8_problem1() { this.head = null; this.tail = null; this.size = 0; } //Insert a node at specifc Location public void insertAt(int value, int index) { Node newNode = new Node(); newNode.data = value; if(head == null){ head = newNode; tail = newNode; head.next...
Implement the following in java. 1. An insertAtBeginning(Node newNode) function, that inserts a node at the beginning(root) of the linked list. 2. A removeFromBeginning() function, that removes the node from the beginning of the linked list and assigns the next element as the new beginning(root). 3. A traverse function, that iterates the list and prints the elements in the linked list. For the insertAtBeginning(Node newNode) function: 1. Check if the root is null. If it is, just assign the new...
Question: SWAPPING NODES IN A SINGULARLY LINKED LIST: I am attempting to create a program that swaps 2 nodes (no matter where they are in the list) and am having some difficulty. I can't seem to figure out why this swap method is throwing an error. Code: (SWAPPING METHOD AND TEST LINE BOLDED) package linkedlists; public class SinglyLinkedList<E> implements Cloneable { //---------------- nested Node class ---------------- /** * Node of a singly linked list, which stores a reference to its...