ReversePoem.java :-
---------------------------------
public class ReversePoem {
/*This programs has you display a pessimistic poem from a list of phrases*/
// and then reverse the phrases to find another more optimistic poem.
public static void main(String[] args) throws Exception
{
//Queue object
MyQueue queue = new MyQueue<>();
//Stack object
MyStack stack = new MyStack<>();
//String buffer to apppend all Strings
StringBuffer sb = new StringBuffer();
// Create a single String object from the 16 Strings below
String set1 = "I am part of a lost generation#and I refuse to believe that#";
sb.append(set1);
String set2 = "I can change the world#I realize this may be a shock but#";
sb.append(set2);
String set3 = "'Happiness comes from within'#is a lie, and#";
sb.append(set3);
String set4 = "'Money will make me happy'#So in 30 years I will tell my children#";
sb.append(set4);
String set5 = "they are not the most important thing in my life#";
sb.append(set5);
String set6 = "My employer will know that#I have my priorities straight because#";
sb.append(set6);
String set7 = "work#is more important than#family#I tell you this#";
sb.append(set7);
String set8 = "Once upon a time#Families stayed together#";
sb.append(set8);
String set9 = "but this will not be true in my era#";
sb.append(set9);
String set10 = "This is a quick fix society#Experts tell me#";
sb.append(set10);
String set11 = "30 years from now, I will be celebrating the 10th anniversary of my
divorce#";
sb.append(set11);
String set12 = "I do not concede that#I will live in a country of my own making#";
sb.append(set12);
String set13 = "In the future#Environmental destruction will be the norm#";
sb.append(set13);
String set14 = "No longer can it be said that#My peers and I care about this earth#";
sb.append(set14);
String set15 = "It will be evident that#My generation is apathetic and lethargic#";
sb.append(set15);
String set16 = "It is foolish to presume that#There is hope#";
sb.append(set16);
String finalString = sb.toString();
String itmes[] = finalString.split("#");
System.out.println("========== Original Phrase ==============");
for(int i = 0 ; i < itmes.length;i++){
queue.enqueue(itmes[i]);
System.out.println(itmes[i]);
}
for(int i = 0 ; i < itmes.length;i++){
stack.push(queue.dequeue());
}
System.out.println("========== Reverse Phrase ==============");
for(int i = 0 ; i < itmes.length;i++){
System.out.println(stack.pop());
}
/* You are given a list of phrases in Strings; the phrases
are separated by pound signs: '#':
1. Create a single String object from this list.
2. Then, split the String of phrases into an array of
phrases using the String split method.
3. Display a poem by walking through the array and
displaying each phrase one per line.
4. And, at the same time, place each phrase on a
MyQueue object using only the enqueue method.
5. After all the phrases have been placed on the queue,
transfer the phrases from the MyQueue object to a
MyStack object using the dequeue and push methods.
6. Then, use the pop method to remove them from the
stack and, at the same time,display the phrases,
one per line.
The result is another poem with the phrases reversed.*/
}
}
MyList.java :-
---------------------------------------
public interface MyList extends java.lang.Iterable
{
// Add a new element at the end of this list
public void add (E e);
// Add a new element at specified index in this list
public void add (int index, E e);
// Return true if this list contains the element
public boolean contains (E e);
// Return the element at the specified index
public E get (int index);
// Return the index of the first matching element
// Return -1 if no match.
public int indexOf (E e);
// Return the index of the last matching element
// Return -1 if no match.
public int lastIndexOf (E e);
// Return true if this list contains no elements
public boolean isEmpty();
// Clear the list
public void clear();
// Remove the first occurrence of the element
// Shift any subsequent elements to the left.
// Return true if the element is removed.
public boolean remove (E e);
// Remove the element at the specified position
// Shift any subsequent elements to the left.
// Return the element that was removed from the list.
public E remove (int index);
// Replace the element at the specified position
// with the specified element and returns the new set.
public Object set (int index, E e);
// Return the number of elements in this list
public int size();
}
MyAbstractList.java :-
---------------------------------------
public abstract class MyAbstractList implements MyList
{
protected int size = 0; // The size of the list
protected MyAbstractList()
{
} // Create a default list
// Create a list from an array of objects
protected MyAbstractList (E[] objects)
{
for (int i = 0; i < objects.length; i++)
{
add (objects[i]);
}
}
// Add a new element at the end of this list
@Override
public void add (E e)
{
add (size, e);
}
// Return true if this list contains no elements
@Override
public boolean isEmpty()
{
return size == 0;
}
// Return the number of elements in this list
@Override
public int size()
{
return size;
}
// Remove the first occurrence of the element e
// Shift any subsequent elements to the left.
// Return true if the element is removed.
@Override
public boolean remove(E e)
{
if (indexOf (e) >= 0)
{
remove (indexOf(e));
return true;
}
else
{
return false;
}
}
}
MyArrayList.java :-
------------------------------
public class MyArrayList extends MyAbstractList
{
public static final int INITIAL_CAPACITY = 16;
private E[] data = null;
public int capacity;
// Create a default list of 16 elements
public MyArrayList()
{
data = (E[]) new Comparable[INITIAL_CAPACITY]; // array
capacity = INITIAL_CAPACITY;
}
// Create a list of capacity elements
public MyArrayList (int capacity)
{
data = (E[]) new Comparable[capacity]; // array
}
// Create a list from an array of objects
public MyArrayList (E[] objects)
{
for (int i = 0; i < objects.length; i++)
{
add (objects[i]); // Warning: don’t use super(objects)!
}
}
// Add a new element at the specified index
@Override
public void add (int index, E e)
{
// Doubles array, if not big enough
ensureCapacity();
// Move the elements to the right after the specified index
for (int i = size - 1; i >= index; i--)
{
data[i + 1] = data[i];
}
// Insert new element to data[index] and increase size
data[index] = e;
size++;
}
// Create a new larger array, double the current size + 1
private void ensureCapacity()
{
if (size >= data.length)
{
E[] newData = (E[]) (new Comparable[size * 2 + 1]);
System.arraycopy (data, 0, newData, 0, size);
data = newData;
}
}
// Return true if this list contains the element
@Override
public boolean contains (E e)
{
for (int i = 0; i < size; i++)
{
if (e.equals(data[i]))
{
return true;
}
}
return false;
}
// Return the element at the specified index
@Override
public E get (int index)
{
checkIndex (index);
return data[index];
}
// Throws IndexOutOfBoundsException, if needed
private void checkIndex (int index)
{
if (index < 0 || index >= size)
{
throw new IndexOutOfBoundsException
("Index: " + index + ", Size: " + size);
}
}
// Return the index of the first matching element
// Return -1 if no match.
@Override
public int indexOf(E e)
{
for (int i = 0; i < size; i++)
{
if (e.equals (data[i]))
{
return i;
}
}
return -1;
}
// Return the index of the last matching element
// Return -1 if no match.
@Override
public int lastIndexOf (E e)
{
for (int i = size - 1; i >= 0; i--)
{
if (e.equals (data[i]))
{
return i;
}
}
return -1;
}
// Remove the element at the specified position
// Shift any subsequent elements to the left.
// Return the element that was removed from the list.
@Override
public E remove(int index)
{
checkIndex (index);
E old = data[index];
// Shift data to the left
for (int j = index; j < size - 1; j++)
{
data[j] = data[j + 1];
}
data[size - 1] = null; // This element is now null
size--; // Decrement size
return old;
}
// Replace the element at the specified position
// with the specified element.
@Override
public E set (int index, E e)
{
checkIndex (index);
E old = data[index];
data[index] = e;
return old;
}
// Return a string representation of the array
@Override
public String toString()
{
StringBuilder result = new StringBuilder("[");
for (int i = 0; i < size; i++)
{
result.append (data[i]);
if (i < size - 1)
{
result.append (", ");
}
}
return result.toString() + "]";
}
// Trims the capacity of the array to the current size
// If size == capacity, no need to trim
public void trimToSize()
{
if (size != data.length)
{
E[] newData = (E[]) (new Comparable[size]);
System.arraycopy (data, 0, newData, 0, size);
data = newData;
}
}
// Clear the array: create a new empty one
@Override
public void clear()
{
data = (E[]) new Comparable[INITIAL_CAPACITY];
size = 0;
}
// Override iterator() defined in Iterable
@Override
public java.util.Iterator iterator()
{
return new ArrayListIterator();
}
// Private iterator class for myArrayList class
private class ArrayListIterator implements java.util.Iterator
{
private int current = 0; // Current index
// Return true when there are more elements past current
@Override
public boolean hasNext()
{
return(current < size);
}
// Return the element at current
@Override
public E next()
{
return data[current++];
}
// Remove the element at current
@Override
public void remove()
{
MyArrayList.this.remove(current);
}
}
}
MyLinkedList.java :-
------------------------------------
public class MyLinkedList extends MyAbstractList
implements Comparable
{
private Node head, tail; // head and tail pointers
// Create a default list
public MyLinkedList()
{
}
// Need this for implementing Comparable
public int compareTo (MyLinkedList e)
{
return(size() - e.size());
}
// Create a list from an array of objects
public MyLinkedList (E[] objects)
{
super(objects); // Passes the array up to abstract parent
}
// Return the head element in the list
public E getFirst()
{
if (size == 0)
{
return null;
}
else
{
return head.element;
}
}
// Return the last element in the list
public E getLast()
{
if (size == 0)
{
return null;
}
else
{
return tail.element;
}
}
// Add an element to the beginning of the list
public void addFirst (E e)
{
// Create a new node for element e
Node newNode = new Node(e);
newNode.next = head; // link the new node with the head
head = newNode; // head points to the new node
size++; // Increase list size
if (tail == null) // new node is only node
{
tail = head;
}
}
// Add an element to the end of the list
public void addLast (E e)
{
// Create a new node for element e
Node newNode = new Node(e);
if (tail == null)
{
head = tail = newNode; // new node is only node
}
else
{
tail.next = newNode; // Link the new with the last node
tail = tail.next; // tail now points to the last node
}
size++; // Increase size
}
// Remove the head node and
// return the object from the removed node
public E removeFirst()
{
if (size == 0)
{
return null;
}
else
{
Node temp = head;
head = head.next;
size--;
if (head == null)
{
tail = null;
}
return temp.element;
}
}
// Remove the last node and return the object from it
public E removeLast()
{
if (size == 0)
{
return null;
}
else if (size == 1)
{
Node temp = head;
head = tail = null;
size = 0;
return temp.element;
}
else
{
Node current = head;
for (int i = 0; i < size - 2; i++)
{
current = current.next;
}
Node temp = tail;
tail = current;
tail.next = null;
size--;
return temp.element;
}
}
// Remove the element at the specified position
// Return the element that was removed from the list.
@Override
public E remove (int index)
{
if (index < 0 || index >= size)
{
return null;
}
else if (index == 0)
{
return removeFirst();
}
else if (index == size - 1)
{
return removeLast();
}
else
{
Node previous = head;
for (int i = 1; i < index; i++)
{
previous = previous.next;
}
Node current = previous.next;
previous.next = current.next;
size--;
return current.element;
}
}
// Return a String representation of the linked list elements
@Override
public String toString()
{
StringBuilder result = new StringBuilder("[");
Node current = head;
for (int i = 0; i < size; i++)
{
result.append (current.element);
current = current.next;
if (current != null)
{
result.append (", "); // Separate elements with a comma
}
else
{
result.append ("]"); // Insert the ] in the string
}
}
return result.toString();
}
// Clear the list
@Override
public void clear()
{
size = 0;
head = tail = null;
}
@Override
// Add a new element at specified index in this list
public void add(int index, E e)
{
if (index == 0)
{
addFirst (e);
}
else if (index == size)
{
addLast (e);
}
else
{
checkIndex (index);
// Create a new node for element e
Node newNode = new Node(e);
Node previous = head;
for (int i = 1; i < index; i++)
{
previous = previous.next;
}
newNode.next = previous.next;
previous.next = newNode;
size++; // Increase size
}
}
// Return true if this list contains the element e
@Override
public boolean contains(E e)
{
Node current = head;
for (int i = 0; i < size; i++)
{
if (current.element == e)
{
return true;
}
current = current.next;
}
return false;
}
// Return the element at the specified index
@Override
public E get (int index)
{
if (index < 0 || index >= size)
{
return null;
}
else
{
Node current = head;
for (int i = 0; i == index; i++)
{
current = current.next;
}
return current.element;
}
}
// Return the index of the first matching element
// Return -1 if no match
@Override
public int indexOf (E e)
{
Node current = head;
for (int i = 0; i < size; i++)
{
if (current.element.equals(e))
{
return i;
}
current = current.next;
}
return -1;
}
// Return the index of the last matching element
// Return -1 if no match.
@Override
public int lastIndexOf (E e)
{
int lastIndex = -1;
Node current = head;
for (int i = 0; i < size; i++)
{
if (e.equals (current.element))
{
lastIndex = i;
}
current = current.next;
}
return lastIndex;
}
// Replace the element at the specified position
// with the specified element
@Override
public E set (int index, E e)
{
Node current = head;
for (int i = 0; i < index; i++)
{
current = current.next;
}
E old = current.element;
current.element = e;
return old;
}
// Override iterator() defined in Iterable
@Override
public java.util.Iterator iterator()
{
return new LinkedListIterator();
}
// Throws IndexOutOfBoundsException, if needed
private void checkIndex (int index)
{
if (index < 0 || index >= size)
{
throw new IndexOutOfBoundsException
("Index: " + index + ", Size: " + size);
}
}
// The Node class
private class Node
{
E element;
Node next;
public Node (E element)
{
this.element = element;
}
}
// Private iterator class for myArrayList class
private class LinkedListIterator implements java.util.Iterator
{
private Node current = head; // Current index
@Override
public boolean hasNext()
{
return(current != null);
}
@Override
public E next()
{
E e = current.element;
current = current.next;
return e;
}
@Override
public void remove()
{
MyLinkedList.this.remove (current.element);
}
}
@Override
public int compareTo(E o) {
// TODO Auto-generated method stub
return 0;
}
}
MyQueue.java :-
-----------------------------
public class MyQueue
{
private MyLinkedList list = new MyLinkedList();
public void enqueue(E e)
{
list.addLast(e);
}
public E dequeue()
{
return (E) list.removeFirst();
}
public int getSize()
{
return list.size();
}
@Override
public String toString()
{
return "Queue: " + list.toString();
}
}
MyStack.java :-
------------------------
public class MyStack implements Comparable
{
private MyArrayList list = new MyArrayList();
// Use this to find top of stack and to compare Stacks
public int getSize()
{
return list.size();
}
// Look at top of stack, without removing it
public E peek()
{
return (E)list.get (getSize() - 1);
}
// Place a new element on the stack
public void push (E e)
{
list.add (e);
}
// Remove the top element from the stack
public E pop()
{
E e = (E)list.get (getSize() - 1);
list.remove (getSize() - 1);
return e;
}
public boolean isEmpty()
{
return list.isEmpty();
}
public int compareTo (MyStack e)
{
return(getSize() - e.getSize());
}
public MyArrayList getList()
{
return list;
}
@Override
public String toString()
{
return "Stack: " + list.toString();
}
@Override
public int compareTo(E o) {
// TODO Auto-generated method stub
return 0;
}
}
Solution
ReversePoem.java :-
---------------------------------
public class ReversePoem {
/*This programs has you display a pessimistic poem from a list of phrases*/
// and then reverse the phrases to find another more optimistic poem.
public static void main(String[] args) throws Exception
{
//Queue object
MyQueue queue = new MyQueue<>();
//Stack object
MyStack stack = new MyStack<>();
//String buffer to apppend all Strings
StringBuffer sb = new StringBuffer();
// Create a single String object from the 16 Strings below
String set1 = "I am part of a lost generation#and I refuse to believe that#";
sb.append(set1);
String set2 = "I can change the world#I realize this may be a shock but#";
sb.append(set2);
String set3 = "'Happiness comes from within'#is a lie, and#";
sb.append(set3);
String set4 = "'Money will make me happy'#So in 30 years I will tell my children#";
sb.append(set4);
String set5 = "they are not the most important thing in my life#";
sb.append(set5);
String set6 = "My employer will know that#I have my priorities straight because#";
sb.append(set6);
String set7 = "work#is more important than#family#I tell you this#";
sb.append(set7);
String set8 = "Once upon a time#Families stayed together#";
sb.append(set8);
String set9 = "but this will not be true in my era#";
sb.append(set9);
String set10 = "This is a quick fix society#Experts tell me#";
sb.append(set10);
String set11 = "30 years from now, I will be celebrating the 10th anniversary of my
divorce#";
sb.append(set11);
String set12 = "I do not concede that#I will live in a country of my own making#";
sb.append(set12);
String set13 = "In the future#Environmental destruction will be the norm#";
sb.append(set13);
String set14 = "No longer can it be said that#My peers and I care about this earth#";
sb.append(set14);
String set15 = "It will be evident that#My generation is apathetic and lethargic#";
sb.append(set15);
String set16 = "It is foolish to presume that#There is hope#";
sb.append(set16);
String finalString = sb.toString();
String itmes[] = finalString.split("#");
System.out.println("========== Original Phrase ==============");
for(int i = 0 ; i < itmes.length;i++){
queue.enqueue(itmes[i]);
System.out.println(itmes[i]);
}
for(int i = 0 ; i < itmes.length;i++){
stack.push(queue.dequeue());
}
System.out.println("========== Reverse Phrase ==============");
for(int i = 0 ; i < itmes.length;i++){
System.out.println(stack.pop());
}
/* You are given a list of phrases in Strings; the phrases
are separated by pound signs: '#':
1. Create a single String object from this list.
2. Then, split the String of phrases into an array of
phrases using the String split method.
3. Display a poem by walking through the array and
displaying each phrase one per line.
4. And, at the same time, place each phrase on a
MyQueue object using only the enqueue method.
5. After all the phrases have been placed on the queue,
transfer the phrases from the MyQueue object to a
MyStack object using the dequeue and push methods.
6. Then, use the pop method to remove them from the
stack and, at the same time,display the phrases,
one per line.
The result is another poem with the phrases reversed.*/
}
}
MyList.java :-
---------------------------------------
public interface MyList extends java.lang.Iterable
{
// Add a new element at the end of this list
public void add (E e);
// Add a new element at specified index in this list
public void add (int index, E e);
// Return true if this list contains the element
public boolean contains (E e);
// Return the element at the specified index
public E get (int index);
// Return the index of the first matching element
// Return -1 if no match.
public int indexOf (E e);
// Return the index of the last matching element
// Return -1 if no match.
public int lastIndexOf (E e);
// Return true if this list contains no elements
public boolean isEmpty();
// Clear the list
public void clear();
// Remove the first occurrence of the element
// Shift any subsequent elements to the left.
// Return true if the element is removed.
public boolean remove (E e);
// Remove the element at the specified position
// Shift any subsequent elements to the left.
// Return the element that was removed from the list.
public E remove (int index);
// Replace the element at the specified position
// with the specified element and returns the new set.
public Object set (int index, E e);
// Return the number of elements in this list
public int size();
}
MyAbstractList.java :-
---------------------------------------
public abstract class MyAbstractList implements MyList
{
protected int size = 0; // The size of the list
protected MyAbstractList()
{
} // Create a default list
// Create a list from an array of objects
protected MyAbstractList (E[] objects)
{
for (int i = 0; i < objects.length; i++)
{
add (objects[i]);
}
}
// Add a new element at the end of this list
@Override
public void add (E e)
{
add (size, e);
}
// Return true if this list contains no elements
@Override
public boolean isEmpty()
{
return size == 0;
}
// Return the number of elements in this list
@Override
public int size()
{
return size;
}
// Remove the first occurrence of the element e
// Shift any subsequent elements to the left.
// Return true if the element is removed.
@Override
public boolean remove(E e)
{
if (indexOf (e) >= 0)
{
remove (indexOf(e));
return true;
}
else
{
return false;
}
}
}
MyArrayList.java :-
------------------------------
public class MyArrayList extends MyAbstractList
{
public static final int INITIAL_CAPACITY = 16;
private E[] data = null;
public int capacity;
// Create a default list of 16 elements
public MyArrayList()
{
data = (E[]) new Comparable[INITIAL_CAPACITY]; // array
capacity = INITIAL_CAPACITY;
}
// Create a list of capacity elements
public MyArrayList (int capacity)
{
data = (E[]) new Comparable[capacity]; // array
}
// Create a list from an array of objects
public MyArrayList (E[] objects)
{
for (int i = 0; i < objects.length; i++)
{
add (objects[i]); // Warning: don’t use super(objects)!
}
}
// Add a new element at the specified index
@Override
public void add (int index, E e)
{
// Doubles array, if not big enough
ensureCapacity();
// Move the elements to the right after the specified index
for (int i = size - 1; i >= index; i--)
{
data[i + 1] = data[i];
}
// Insert new element to data[index] and increase size
data[index] = e;
size++;
}
// Create a new larger array, double the current size + 1
private void ensureCapacity()
{
if (size >= data.length)
{
E[] newData = (E[]) (new Comparable[size * 2 + 1]);
System.arraycopy (data, 0, newData, 0, size);
data = newData;
}
}
// Return true if this list contains the element
@Override
public boolean contains (E e)
{
for (int i = 0; i < size; i++)
{
if (e.equals(data[i]))
{
return true;
}
}
return false;
}
// Return the element at the specified index
@Override
public E get (int index)
{
checkIndex (index);
return data[index];
}
// Throws IndexOutOfBoundsException, if needed
private void checkIndex (int index)
{
if (index < 0 || index >= size)
{
throw new IndexOutOfBoundsException
("Index: " + index + ", Size: " + size);
}
}
// Return the index of the first matching element
// Return -1 if no match.
@Override
public int indexOf(E e)
{
for (int i = 0; i < size; i++)
{
if (e.equals (data[i]))
{
return i;
}
}
return -1;
}
// Return the index of the last matching element
// Return -1 if no match.
@Override
public int lastIndexOf (E e)
{
for (int i = size - 1; i >= 0; i--)
{
if (e.equals (data[i]))
{
return i;
}
}
return -1;
}
// Remove the element at the specified position
// Shift any subsequent elements to the left.
// Return the element that was removed from the list.
@Override
public E remove(int index)
{
checkIndex (index);
E old = data[index];
// Shift data to the left
for (int j = index; j < size - 1; j++)
{
data[j] = data[j + 1];
}
data[size - 1] = null; // This element is now null
size--; // Decrement size
return old;
}
// Replace the element at the specified position
// with the specified element.
@Override
public E set (int index, E e)
{
checkIndex (index);
E old = data[index];
data[index] = e;
return old;
}
// Return a string representation of the array
@Override
public String toString()
{
StringBuilder result = new StringBuilder("[");
for (int i = 0; i < size; i++)
{
result.append (data[i]);
if (i < size - 1)
{
result.append (", ");
}
}
return result.toString() + "]";
}
// Trims the capacity of the array to the current size
// If size == capacity, no need to trim
public void trimToSize()
{
if (size != data.length)
{
E[] newData = (E[]) (new Comparable[size]);
System.arraycopy (data, 0, newData, 0, size);
data = newData;
}
}
// Clear the array: create a new empty one
@Override
public void clear()
{
data = (E[]) new Comparable[INITIAL_CAPACITY];
size = 0;
}
// Override iterator() defined in Iterable
@Override
public java.util.Iterator iterator()
{
return new ArrayListIterator();
}
// Private iterator class for myArrayList class
private class ArrayListIterator implements java.util.Iterator
{
private int current = 0; // Current index
// Return true when there are more elements past current
@Override
public boolean hasNext()
{
return(current < size);
}
// Return the element at current
@Override
public E next()
{
return data[current++];
}
// Remove the element at current
@Override
public void remove()
{
MyArrayList.this.remove(current);
}
}
}
MyLinkedList.java :-
------------------------------------
public class MyLinkedList extends MyAbstractList
implements Comparable
{
private Node head, tail; // head and tail pointers
// Create a default list
public MyLinkedList()
{
}
// Need this for implementing Comparable
public int compareTo (MyLinkedList e)
{
return(size() - e.size());
}
// Create a list from an array of objects
public MyLinkedList (E[] objects)
{
super(objects); // Passes the array up to abstract parent
}
// Return the head element in the list
public E getFirst()
{
if (size == 0)
{
return null;
}
else
{
return head.element;
}
}
// Return the last element in the list
public E getLast()
{
if (size == 0)
{
return null;
}
else
{
return tail.element;
}
}
// Add an element to the beginning of the list
public void addFirst (E e)
{
// Create a new node for element e
Node newNode = new Node(e);
newNode.next = head; // link the new node with the head
head = newNode; // head points to the new node
size++; // Increase list size
if (tail == null) // new node is only node
{
tail = head;
}
}
// Add an element to the end of the list
public void addLast (E e)
{
// Create a new node for element e
Node newNode = new Node(e);
if (tail == null)
{
head = tail = newNode; // new node is only node
}
else
{
tail.next = newNode; // Link the new with the last node
tail = tail.next; // tail now points to the last node
}
size++; // Increase size
}
// Remove the head node and
// return the object from the removed node
public E removeFirst()
{
if (size == 0)
{
return null;
}
else
{
Node temp = head;
head = head.next;
size--;
if (head == null)
{
tail = null;
}
return temp.element;
}
}
// Remove the last node and return the object from it
public E removeLast()
{
if (size == 0)
{
return null;
}
else if (size == 1)
{
Node temp = head;
head = tail = null;
size = 0;
return temp.element;
}
else
{
Node current = head;
for (int i = 0; i < size - 2; i++)
{
current = current.next;
}
Node temp = tail;
tail = current;
tail.next = null;
size--;
return temp.element;
}
}
// Remove the element at the specified position
// Return the element that was removed from the list.
@Override
public E remove (int index)
{
if (index < 0 || index >= size)
{
return null;
}
else if (index == 0)
{
return removeFirst();
}
else if (index == size - 1)
{
return removeLast();
}
else
{
Node previous = head;
for (int i = 1; i < index; i++)
{
previous = previous.next;
}
Node current = previous.next;
previous.next = current.next;
size--;
return current.element;
}
}
// Return a String representation of the linked list elements
@Override
public String toString()
{
StringBuilder result = new StringBuilder("[");
Node current = head;
for (int i = 0; i < size; i++)
{
result.append (current.element);
current = current.next;
if (current != null)
{
result.append (", "); // Separate elements with a comma
}
else
{
result.append ("]"); // Insert the ] in the string
}
}
return result.toString();
}
// Clear the list
@Override
public void clear()
{
size = 0;
head = tail = null;
}
@Override
// Add a new element at specified index in this list
public void add(int index, E e)
{
if (index == 0)
{
addFirst (e);
}
else if (index == size)
{
addLast (e);
}
else
{
checkIndex (index);
// Create a new node for element e
Node newNode = new Node(e);
Node previous = head;
for (int i = 1; i < index; i++)
{
previous = previous.next;
}
newNode.next = previous.next;
previous.next = newNode;
size++; // Increase size
}
}
// Return true if this list contains the element e
@Override
public boolean contains(E e)
{
Node current = head;
for (int i = 0; i < size; i++)
{
if (current.element == e)
{
return true;
}
current = current.next;
}
return false;
}
// Return the element at the specified index
@Override
public E get (int index)
{
if (index < 0 || index >= size)
{
return null;
}
else
{
Node current = head;
for (int i = 0; i == index; i++)
{
current = current.next;
}
return current.element;
}
}
// Return the index of the first matching element
// Return -1 if no match
@Override
public int indexOf (E e)
{
Node current = head;
for (int i = 0; i < size; i++)
{
if (current.element.equals(e))
{
return i;
}
current = current.next;
}
return -1;
}
// Return the index of the last matching element
// Return -1 if no match.
@Override
public int lastIndexOf (E e)
{
int lastIndex = -1;
Node current = head;
for (int i = 0; i < size; i++)
{
if (e.equals (current.element))
{
lastIndex = i;
}
current = current.next;
}
return lastIndex;
}
// Replace the element at the specified position
// with the specified element
@Override
public E set (int index, E e)
{
Node current = head;
for (int i = 0; i < index; i++)
{
current = current.next;
}
E old = current.element;
current.element = e;
return old;
}
// Override iterator() defined in Iterable
@Override
public java.util.Iterator iterator()
{
return new LinkedListIterator();
}
// Throws IndexOutOfBoundsException, if needed
private void checkIndex (int index)
{
if (index < 0 || index >= size)
{
throw new IndexOutOfBoundsException
("Index: " + index + ", Size: " + size);
}
}
// The Node class
private class Node
{
E element;
Node next;
public Node (E element)
{
this.element = element;
}
}
// Private iterator class for myArrayList class
private class LinkedListIterator implements java.util.Iterator
{
private Node current = head; // Current index
@Override
public boolean hasNext()
{
return(current != null);
}
@Override
public E next()
{
E e = current.element;
current = current.next;
return e;
}
@Override
public void remove()
{
MyLinkedList.this.remove (current.element);
}
}
@Override
public int compareTo(E o) {
// TODO Auto-generated method stub
return 0;
}
}
MyQueue.java :-
-----------------------------
public class MyQueue
{
private MyLinkedList list = new MyLinkedList();
public void enqueue(E e)
{
list.addLast(e);
}
public E dequeue()
{
return (E) list.removeFirst();
}
public int getSize()
{
return list.size();
}
@Override
public String toString()
{
return "Queue: " + list.toString();
}
}
MyStack.java :-
------------------------
public class MyStack implements Comparable
{
private MyArrayList list = new MyArrayList();
// Use this to find top of stack and to compare Stacks
public int getSize()
{
return list.size();
}
// Look at top of stack, without removing it
public E peek()
{
return (E)list.get (getSize() - 1);
}
// Place a new element on the stack
public void push (E e)
{
list.add (e);
}
// Remove the top element from the stack
public E pop()
{
E e = (E)list.get (getSize() - 1);
list.remove (getSize() - 1);
return e;
}
public boolean isEmpty()
{
return list.isEmpty();
}
public int compareTo (MyStack e)
{
return(getSize() - e.getSize());
}
public MyArrayList getList()
{
return list;
}
@Override
public String toString()
{
return "Stack: " + list.toString();
}
@Override
public int compareTo(E o) {
// TODO Auto-generated method stub
return 0;
}
}

More Related Content

PDF
Everything needs to be according to the instructions- thank you! SUPPO.pdf
DOCX
Please complete all the code as per instructions in Java programming.docx
PDF
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdf
PDF
Given below is the completed implementation of MyLinkedList class. O.pdf
DOCX
JAVA Demonstrate the use of your APL in a PartB_Driver class by doing.docx
PDF
STAGE 2 The Methods 65 points Implement all the methods t.pdf
PDF
Note- Can someone help me with the public boolean isEmpty()- public bo.pdf
PDF
I need help with this code working Create another project and add yo.pdf
Everything needs to be according to the instructions- thank you! SUPPO.pdf
Please complete all the code as per instructions in Java programming.docx
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdf
Given below is the completed implementation of MyLinkedList class. O.pdf
JAVA Demonstrate the use of your APL in a PartB_Driver class by doing.docx
STAGE 2 The Methods 65 points Implement all the methods t.pdf
Note- Can someone help me with the public boolean isEmpty()- public bo.pdf
I need help with this code working Create another project and add yo.pdf

Similar to ReversePoem.java ---------------------------------- public cl.pdf (20)

PPT
A2003822018_21789_17_2018_09. ArrayList.ppt
PDF
File LinkedList.java Defines a doubly-l.pdf
PDF
For each task, submit your source java code file.(1) Objective Im.pdf
PDF
public class MyLinkedListltE extends ComparableltEgtg.pdf
PDF
Hi,I have added the methods and main class as per your requirement.pdf
PDF
Copy your completed LinkedList class from Lab 3 into the LinkedList..pdf
DOCX
Array list
PDF
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
PDF
output and explain There is Mylist There is MyArrayList pa.pdf
PDF
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
PPT
Engineering lecture ppt by venay magen
PPT
lec6.ppt
PDF
Please help me to make a programming project I have to sue them today- (1).pdf
PDF
Write a Java Class to Implement a Generic Linked ListYour list mus.pdf
PDF
The LinkedList1 class implements a Linked list. class.pdf
PPTX
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
PDF
Class DiagramIn the Assignment #10, you are given three files Ass.pdf
PDF
LabProgram.javaimport java.util.NoSuchElementException;public .pdf
PDF
Implement the additional 5 methods as indicated in the LinkedList fi.pdf
PPT
L11 array list
A2003822018_21789_17_2018_09. ArrayList.ppt
File LinkedList.java Defines a doubly-l.pdf
For each task, submit your source java code file.(1) Objective Im.pdf
public class MyLinkedListltE extends ComparableltEgtg.pdf
Hi,I have added the methods and main class as per your requirement.pdf
Copy your completed LinkedList class from Lab 3 into the LinkedList..pdf
Array list
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
output and explain There is Mylist There is MyArrayList pa.pdf
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
Engineering lecture ppt by venay magen
lec6.ppt
Please help me to make a programming project I have to sue them today- (1).pdf
Write a Java Class to Implement a Generic Linked ListYour list mus.pdf
The LinkedList1 class implements a Linked list. class.pdf
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
Class DiagramIn the Assignment #10, you are given three files Ass.pdf
LabProgram.javaimport java.util.NoSuchElementException;public .pdf
Implement the additional 5 methods as indicated in the LinkedList fi.pdf
L11 array list
Ad

More from ravikapoorindia (20)

PDF
1.The Excavata includes taxa that are photosynthetic, parasitic, sym.pdf
PDF
1. According to morphological species concept focus on external phys.pdf
PDF
1)calcium(pH-dependent regulation of lysosomal calcium in macrophage.pdf
PDF
Viral genomes may be circular, as in the polyomaviruses, or linear, .pdf
PDF
True. gaps are the reason for electrical conductivity.Solution.pdf
PDF
This is an example of a Lewis Acid. The CO2 acts like an acid becaus.pdf
PDF
The Vestibular System, which is a contributed to our balance system .pdf
PDF
The inherent risk for an assertion about a derivative is its suscept.pdf
PDF
Solution I ) Average inventory = $610,000 5 = $122000Total Inven.pdf
PDF
1 D2 the decrease in entropy of the system is offset by an incr.pdf
PDF
NaCl + H2OSolutionNaCl + H2O.pdf
PDF
Miller is US based investor and co-founder and current chairman of U.pdf
PDF
Marijuana plant belongs to the genus Cannabis. It is native to the C.pdf
PDF
InheritenceJava supports inheritance and thus, variables and metho.pdf
PDF
It is the temporal lobe of cerebrum. It is situated beneath the late.pdf
PDF
In cat,The ductus deferens also called the vas deferens leaves the t.pdf
PDF
LeadCarbonate PbCO3 is ionic compound. electrostaticforces.pdf
PDF
PDF
Lithium has 3 electrons. Since an s orbital only .pdf
PDF
IO3- only exhibitsresonance ,since the lone pairs.pdf
1.The Excavata includes taxa that are photosynthetic, parasitic, sym.pdf
1. According to morphological species concept focus on external phys.pdf
1)calcium(pH-dependent regulation of lysosomal calcium in macrophage.pdf
Viral genomes may be circular, as in the polyomaviruses, or linear, .pdf
True. gaps are the reason for electrical conductivity.Solution.pdf
This is an example of a Lewis Acid. The CO2 acts like an acid becaus.pdf
The Vestibular System, which is a contributed to our balance system .pdf
The inherent risk for an assertion about a derivative is its suscept.pdf
Solution I ) Average inventory = $610,000 5 = $122000Total Inven.pdf
1 D2 the decrease in entropy of the system is offset by an incr.pdf
NaCl + H2OSolutionNaCl + H2O.pdf
Miller is US based investor and co-founder and current chairman of U.pdf
Marijuana plant belongs to the genus Cannabis. It is native to the C.pdf
InheritenceJava supports inheritance and thus, variables and metho.pdf
It is the temporal lobe of cerebrum. It is situated beneath the late.pdf
In cat,The ductus deferens also called the vas deferens leaves the t.pdf
LeadCarbonate PbCO3 is ionic compound. electrostaticforces.pdf
Lithium has 3 electrons. Since an s orbital only .pdf
IO3- only exhibitsresonance ,since the lone pairs.pdf
Ad

Recently uploaded (20)

PDF
Environmental Education MCQ BD2EE - Share Source.pdf
PDF
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
PPTX
Chinmaya Tiranga Azadi Quiz (Class 7-8 )
PDF
HVAC Specification 2024 according to central public works department
PPTX
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
PPTX
Virtual and Augmented Reality in Current Scenario
PDF
International_Financial_Reporting_Standa.pdf
PDF
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
PDF
Empowerment Technology for Senior High School Guide
PDF
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
PDF
Trump Administration's workforce development strategy
PPTX
Computer Architecture Input Output Memory.pptx
PDF
David L Page_DCI Research Study Journey_how Methodology can inform one's prac...
PDF
Weekly quiz Compilation Jan -July 25.pdf
PDF
Uderstanding digital marketing and marketing stratergie for engaging the digi...
PDF
Practical Manual AGRO-233 Principles and Practices of Natural Farming
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PPTX
A powerpoint presentation on the Revised K-10 Science Shaping Paper
PDF
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 2).pdf
PDF
LDMMIA Reiki Yoga Finals Review Spring Summer
Environmental Education MCQ BD2EE - Share Source.pdf
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
Chinmaya Tiranga Azadi Quiz (Class 7-8 )
HVAC Specification 2024 according to central public works department
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
Virtual and Augmented Reality in Current Scenario
International_Financial_Reporting_Standa.pdf
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
Empowerment Technology for Senior High School Guide
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
Trump Administration's workforce development strategy
Computer Architecture Input Output Memory.pptx
David L Page_DCI Research Study Journey_how Methodology can inform one's prac...
Weekly quiz Compilation Jan -July 25.pdf
Uderstanding digital marketing and marketing stratergie for engaging the digi...
Practical Manual AGRO-233 Principles and Practices of Natural Farming
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
A powerpoint presentation on the Revised K-10 Science Shaping Paper
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 2).pdf
LDMMIA Reiki Yoga Finals Review Spring Summer

ReversePoem.java ---------------------------------- public cl.pdf

  • 1. ReversePoem.java :- --------------------------------- public class ReversePoem { /*This programs has you display a pessimistic poem from a list of phrases*/ // and then reverse the phrases to find another more optimistic poem. public static void main(String[] args) throws Exception { //Queue object MyQueue queue = new MyQueue<>(); //Stack object MyStack stack = new MyStack<>(); //String buffer to apppend all Strings StringBuffer sb = new StringBuffer(); // Create a single String object from the 16 Strings below String set1 = "I am part of a lost generation#and I refuse to believe that#"; sb.append(set1); String set2 = "I can change the world#I realize this may be a shock but#"; sb.append(set2); String set3 = "'Happiness comes from within'#is a lie, and#"; sb.append(set3); String set4 = "'Money will make me happy'#So in 30 years I will tell my children#"; sb.append(set4); String set5 = "they are not the most important thing in my life#"; sb.append(set5); String set6 = "My employer will know that#I have my priorities straight because#"; sb.append(set6); String set7 = "work#is more important than#family#I tell you this#"; sb.append(set7); String set8 = "Once upon a time#Families stayed together#"; sb.append(set8); String set9 = "but this will not be true in my era#";
  • 2. sb.append(set9); String set10 = "This is a quick fix society#Experts tell me#"; sb.append(set10); String set11 = "30 years from now, I will be celebrating the 10th anniversary of my divorce#"; sb.append(set11); String set12 = "I do not concede that#I will live in a country of my own making#"; sb.append(set12); String set13 = "In the future#Environmental destruction will be the norm#"; sb.append(set13); String set14 = "No longer can it be said that#My peers and I care about this earth#"; sb.append(set14); String set15 = "It will be evident that#My generation is apathetic and lethargic#"; sb.append(set15); String set16 = "It is foolish to presume that#There is hope#"; sb.append(set16); String finalString = sb.toString(); String itmes[] = finalString.split("#"); System.out.println("========== Original Phrase =============="); for(int i = 0 ; i < itmes.length;i++){ queue.enqueue(itmes[i]); System.out.println(itmes[i]); } for(int i = 0 ; i < itmes.length;i++){ stack.push(queue.dequeue()); } System.out.println("========== Reverse Phrase =============="); for(int i = 0 ; i < itmes.length;i++){ System.out.println(stack.pop()); } /* You are given a list of phrases in Strings; the phrases are separated by pound signs: '#':
  • 3. 1. Create a single String object from this list. 2. Then, split the String of phrases into an array of phrases using the String split method. 3. Display a poem by walking through the array and displaying each phrase one per line. 4. And, at the same time, place each phrase on a MyQueue object using only the enqueue method. 5. After all the phrases have been placed on the queue, transfer the phrases from the MyQueue object to a MyStack object using the dequeue and push methods. 6. Then, use the pop method to remove them from the stack and, at the same time,display the phrases, one per line. The result is another poem with the phrases reversed.*/ } } MyList.java :- --------------------------------------- public interface MyList extends java.lang.Iterable { // Add a new element at the end of this list public void add (E e); // Add a new element at specified index in this list public void add (int index, E e); // Return true if this list contains the element public boolean contains (E e); // Return the element at the specified index public E get (int index); // Return the index of the first matching element // Return -1 if no match. public int indexOf (E e); // Return the index of the last matching element // Return -1 if no match. public int lastIndexOf (E e); // Return true if this list contains no elements
  • 4. public boolean isEmpty(); // Clear the list public void clear(); // Remove the first occurrence of the element // Shift any subsequent elements to the left. // Return true if the element is removed. public boolean remove (E e); // Remove the element at the specified position // Shift any subsequent elements to the left. // Return the element that was removed from the list. public E remove (int index); // Replace the element at the specified position // with the specified element and returns the new set. public Object set (int index, E e); // Return the number of elements in this list public int size(); } MyAbstractList.java :- --------------------------------------- public abstract class MyAbstractList implements MyList { protected int size = 0; // The size of the list protected MyAbstractList() { } // Create a default list // Create a list from an array of objects protected MyAbstractList (E[] objects) { for (int i = 0; i < objects.length; i++) { add (objects[i]); } }
  • 5. // Add a new element at the end of this list @Override public void add (E e) { add (size, e); } // Return true if this list contains no elements @Override public boolean isEmpty() { return size == 0; } // Return the number of elements in this list @Override public int size() { return size; } // Remove the first occurrence of the element e // Shift any subsequent elements to the left. // Return true if the element is removed. @Override public boolean remove(E e) { if (indexOf (e) >= 0) { remove (indexOf(e)); return true; } else { return false; } } } MyArrayList.java :-
  • 6. ------------------------------ public class MyArrayList extends MyAbstractList { public static final int INITIAL_CAPACITY = 16; private E[] data = null; public int capacity; // Create a default list of 16 elements public MyArrayList() { data = (E[]) new Comparable[INITIAL_CAPACITY]; // array capacity = INITIAL_CAPACITY; } // Create a list of capacity elements public MyArrayList (int capacity) { data = (E[]) new Comparable[capacity]; // array } // Create a list from an array of objects public MyArrayList (E[] objects) { for (int i = 0; i < objects.length; i++) { add (objects[i]); // Warning: don’t use super(objects)! } } // Add a new element at the specified index @Override public void add (int index, E e) { // Doubles array, if not big enough ensureCapacity(); // Move the elements to the right after the specified index for (int i = size - 1; i >= index; i--) { data[i + 1] = data[i]; }
  • 7. // Insert new element to data[index] and increase size data[index] = e; size++; } // Create a new larger array, double the current size + 1 private void ensureCapacity() { if (size >= data.length) { E[] newData = (E[]) (new Comparable[size * 2 + 1]); System.arraycopy (data, 0, newData, 0, size); data = newData; } } // Return true if this list contains the element @Override public boolean contains (E e) { for (int i = 0; i < size; i++) { if (e.equals(data[i])) { return true; } } return false; } // Return the element at the specified index @Override public E get (int index) { checkIndex (index); return data[index]; } // Throws IndexOutOfBoundsException, if needed private void checkIndex (int index)
  • 8. { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException ("Index: " + index + ", Size: " + size); } } // Return the index of the first matching element // Return -1 if no match. @Override public int indexOf(E e) { for (int i = 0; i < size; i++) { if (e.equals (data[i])) { return i; } } return -1; } // Return the index of the last matching element // Return -1 if no match. @Override public int lastIndexOf (E e) { for (int i = size - 1; i >= 0; i--) { if (e.equals (data[i])) { return i; } } return -1; } // Remove the element at the specified position
  • 9. // Shift any subsequent elements to the left. // Return the element that was removed from the list. @Override public E remove(int index) { checkIndex (index); E old = data[index]; // Shift data to the left for (int j = index; j < size - 1; j++) { data[j] = data[j + 1]; } data[size - 1] = null; // This element is now null size--; // Decrement size return old; } // Replace the element at the specified position // with the specified element. @Override public E set (int index, E e) { checkIndex (index); E old = data[index]; data[index] = e; return old; } // Return a string representation of the array @Override public String toString() { StringBuilder result = new StringBuilder("["); for (int i = 0; i < size; i++) { result.append (data[i]); if (i < size - 1) {
  • 10. result.append (", "); } } return result.toString() + "]"; } // Trims the capacity of the array to the current size // If size == capacity, no need to trim public void trimToSize() { if (size != data.length) { E[] newData = (E[]) (new Comparable[size]); System.arraycopy (data, 0, newData, 0, size); data = newData; } } // Clear the array: create a new empty one @Override public void clear() { data = (E[]) new Comparable[INITIAL_CAPACITY]; size = 0; } // Override iterator() defined in Iterable @Override public java.util.Iterator iterator() { return new ArrayListIterator(); } // Private iterator class for myArrayList class private class ArrayListIterator implements java.util.Iterator { private int current = 0; // Current index // Return true when there are more elements past current @Override public boolean hasNext()
  • 11. { return(current < size); } // Return the element at current @Override public E next() { return data[current++]; } // Remove the element at current @Override public void remove() { MyArrayList.this.remove(current); } } } MyLinkedList.java :- ------------------------------------ public class MyLinkedList extends MyAbstractList implements Comparable { private Node head, tail; // head and tail pointers // Create a default list public MyLinkedList() { } // Need this for implementing Comparable public int compareTo (MyLinkedList e) { return(size() - e.size()); } // Create a list from an array of objects public MyLinkedList (E[] objects) { super(objects); // Passes the array up to abstract parent
  • 12. } // Return the head element in the list public E getFirst() { if (size == 0) { return null; } else { return head.element; } } // Return the last element in the list public E getLast() { if (size == 0) { return null; } else { return tail.element; } } // Add an element to the beginning of the list public void addFirst (E e) { // Create a new node for element e Node newNode = new Node(e); newNode.next = head; // link the new node with the head head = newNode; // head points to the new node size++; // Increase list size if (tail == null) // new node is only node { tail = head;
  • 13. } } // Add an element to the end of the list public void addLast (E e) { // Create a new node for element e Node newNode = new Node(e); if (tail == null) { head = tail = newNode; // new node is only node } else { tail.next = newNode; // Link the new with the last node tail = tail.next; // tail now points to the last node } size++; // Increase size } // Remove the head node and // return the object from the removed node public E removeFirst() { if (size == 0) { return null; } else { Node temp = head; head = head.next; size--; if (head == null) { tail = null; } return temp.element;
  • 14. } } // Remove the last node and return the object from it public E removeLast() { if (size == 0) { return null; } else if (size == 1) { Node temp = head; head = tail = null; size = 0; return temp.element; } else { Node current = head; for (int i = 0; i < size - 2; i++) { current = current.next; } Node temp = tail; tail = current; tail.next = null; size--; return temp.element; } } // Remove the element at the specified position // Return the element that was removed from the list. @Override public E remove (int index) { if (index < 0 || index >= size)
  • 15. { return null; } else if (index == 0) { return removeFirst(); } else if (index == size - 1) { return removeLast(); } else { Node previous = head; for (int i = 1; i < index; i++) { previous = previous.next; } Node current = previous.next; previous.next = current.next; size--; return current.element; } } // Return a String representation of the linked list elements @Override public String toString() { StringBuilder result = new StringBuilder("["); Node current = head; for (int i = 0; i < size; i++) { result.append (current.element); current = current.next; if (current != null) {
  • 16. result.append (", "); // Separate elements with a comma } else { result.append ("]"); // Insert the ] in the string } } return result.toString(); } // Clear the list @Override public void clear() { size = 0; head = tail = null; } @Override // Add a new element at specified index in this list public void add(int index, E e) { if (index == 0) { addFirst (e); } else if (index == size) { addLast (e); } else { checkIndex (index); // Create a new node for element e Node newNode = new Node(e); Node previous = head; for (int i = 1; i < index; i++) {
  • 17. previous = previous.next; } newNode.next = previous.next; previous.next = newNode; size++; // Increase size } } // Return true if this list contains the element e @Override public boolean contains(E e) { Node current = head; for (int i = 0; i < size; i++) { if (current.element == e) { return true; } current = current.next; } return false; } // Return the element at the specified index @Override public E get (int index) { if (index < 0 || index >= size) { return null; } else { Node current = head; for (int i = 0; i == index; i++) { current = current.next;
  • 18. } return current.element; } } // Return the index of the first matching element // Return -1 if no match @Override public int indexOf (E e) { Node current = head; for (int i = 0; i < size; i++) { if (current.element.equals(e)) { return i; } current = current.next; } return -1; } // Return the index of the last matching element // Return -1 if no match. @Override public int lastIndexOf (E e) { int lastIndex = -1; Node current = head; for (int i = 0; i < size; i++) { if (e.equals (current.element)) { lastIndex = i; } current = current.next; } return lastIndex;
  • 19. } // Replace the element at the specified position // with the specified element @Override public E set (int index, E e) { Node current = head; for (int i = 0; i < index; i++) { current = current.next; } E old = current.element; current.element = e; return old; } // Override iterator() defined in Iterable @Override public java.util.Iterator iterator() { return new LinkedListIterator(); } // Throws IndexOutOfBoundsException, if needed private void checkIndex (int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException ("Index: " + index + ", Size: " + size); } } // The Node class private class Node { E element; Node next; public Node (E element)
  • 20. { this.element = element; } } // Private iterator class for myArrayList class private class LinkedListIterator implements java.util.Iterator { private Node current = head; // Current index @Override public boolean hasNext() { return(current != null); } @Override public E next() { E e = current.element; current = current.next; return e; } @Override public void remove() { MyLinkedList.this.remove (current.element); } } @Override public int compareTo(E o) { // TODO Auto-generated method stub return 0; } } MyQueue.java :- ----------------------------- public class MyQueue {
  • 21. private MyLinkedList list = new MyLinkedList(); public void enqueue(E e) { list.addLast(e); } public E dequeue() { return (E) list.removeFirst(); } public int getSize() { return list.size(); } @Override public String toString() { return "Queue: " + list.toString(); } } MyStack.java :- ------------------------ public class MyStack implements Comparable { private MyArrayList list = new MyArrayList(); // Use this to find top of stack and to compare Stacks public int getSize() { return list.size(); } // Look at top of stack, without removing it public E peek() { return (E)list.get (getSize() - 1); } // Place a new element on the stack public void push (E e)
  • 22. { list.add (e); } // Remove the top element from the stack public E pop() { E e = (E)list.get (getSize() - 1); list.remove (getSize() - 1); return e; } public boolean isEmpty() { return list.isEmpty(); } public int compareTo (MyStack e) { return(getSize() - e.getSize()); } public MyArrayList getList() { return list; } @Override public String toString() { return "Stack: " + list.toString(); } @Override public int compareTo(E o) { // TODO Auto-generated method stub return 0; } } Solution
  • 23. ReversePoem.java :- --------------------------------- public class ReversePoem { /*This programs has you display a pessimistic poem from a list of phrases*/ // and then reverse the phrases to find another more optimistic poem. public static void main(String[] args) throws Exception { //Queue object MyQueue queue = new MyQueue<>(); //Stack object MyStack stack = new MyStack<>(); //String buffer to apppend all Strings StringBuffer sb = new StringBuffer(); // Create a single String object from the 16 Strings below String set1 = "I am part of a lost generation#and I refuse to believe that#"; sb.append(set1); String set2 = "I can change the world#I realize this may be a shock but#"; sb.append(set2); String set3 = "'Happiness comes from within'#is a lie, and#"; sb.append(set3); String set4 = "'Money will make me happy'#So in 30 years I will tell my children#"; sb.append(set4); String set5 = "they are not the most important thing in my life#"; sb.append(set5); String set6 = "My employer will know that#I have my priorities straight because#"; sb.append(set6); String set7 = "work#is more important than#family#I tell you this#"; sb.append(set7); String set8 = "Once upon a time#Families stayed together#"; sb.append(set8); String set9 = "but this will not be true in my era#"; sb.append(set9);
  • 24. String set10 = "This is a quick fix society#Experts tell me#"; sb.append(set10); String set11 = "30 years from now, I will be celebrating the 10th anniversary of my divorce#"; sb.append(set11); String set12 = "I do not concede that#I will live in a country of my own making#"; sb.append(set12); String set13 = "In the future#Environmental destruction will be the norm#"; sb.append(set13); String set14 = "No longer can it be said that#My peers and I care about this earth#"; sb.append(set14); String set15 = "It will be evident that#My generation is apathetic and lethargic#"; sb.append(set15); String set16 = "It is foolish to presume that#There is hope#"; sb.append(set16); String finalString = sb.toString(); String itmes[] = finalString.split("#"); System.out.println("========== Original Phrase =============="); for(int i = 0 ; i < itmes.length;i++){ queue.enqueue(itmes[i]); System.out.println(itmes[i]); } for(int i = 0 ; i < itmes.length;i++){ stack.push(queue.dequeue()); } System.out.println("========== Reverse Phrase =============="); for(int i = 0 ; i < itmes.length;i++){ System.out.println(stack.pop()); } /* You are given a list of phrases in Strings; the phrases are separated by pound signs: '#': 1. Create a single String object from this list.
  • 25. 2. Then, split the String of phrases into an array of phrases using the String split method. 3. Display a poem by walking through the array and displaying each phrase one per line. 4. And, at the same time, place each phrase on a MyQueue object using only the enqueue method. 5. After all the phrases have been placed on the queue, transfer the phrases from the MyQueue object to a MyStack object using the dequeue and push methods. 6. Then, use the pop method to remove them from the stack and, at the same time,display the phrases, one per line. The result is another poem with the phrases reversed.*/ } } MyList.java :- --------------------------------------- public interface MyList extends java.lang.Iterable { // Add a new element at the end of this list public void add (E e); // Add a new element at specified index in this list public void add (int index, E e); // Return true if this list contains the element public boolean contains (E e); // Return the element at the specified index public E get (int index); // Return the index of the first matching element // Return -1 if no match. public int indexOf (E e); // Return the index of the last matching element // Return -1 if no match. public int lastIndexOf (E e); // Return true if this list contains no elements public boolean isEmpty();
  • 26. // Clear the list public void clear(); // Remove the first occurrence of the element // Shift any subsequent elements to the left. // Return true if the element is removed. public boolean remove (E e); // Remove the element at the specified position // Shift any subsequent elements to the left. // Return the element that was removed from the list. public E remove (int index); // Replace the element at the specified position // with the specified element and returns the new set. public Object set (int index, E e); // Return the number of elements in this list public int size(); } MyAbstractList.java :- --------------------------------------- public abstract class MyAbstractList implements MyList { protected int size = 0; // The size of the list protected MyAbstractList() { } // Create a default list // Create a list from an array of objects protected MyAbstractList (E[] objects) { for (int i = 0; i < objects.length; i++) { add (objects[i]); } } // Add a new element at the end of this list
  • 27. @Override public void add (E e) { add (size, e); } // Return true if this list contains no elements @Override public boolean isEmpty() { return size == 0; } // Return the number of elements in this list @Override public int size() { return size; } // Remove the first occurrence of the element e // Shift any subsequent elements to the left. // Return true if the element is removed. @Override public boolean remove(E e) { if (indexOf (e) >= 0) { remove (indexOf(e)); return true; } else { return false; } } } MyArrayList.java :- ------------------------------
  • 28. public class MyArrayList extends MyAbstractList { public static final int INITIAL_CAPACITY = 16; private E[] data = null; public int capacity; // Create a default list of 16 elements public MyArrayList() { data = (E[]) new Comparable[INITIAL_CAPACITY]; // array capacity = INITIAL_CAPACITY; } // Create a list of capacity elements public MyArrayList (int capacity) { data = (E[]) new Comparable[capacity]; // array } // Create a list from an array of objects public MyArrayList (E[] objects) { for (int i = 0; i < objects.length; i++) { add (objects[i]); // Warning: don’t use super(objects)! } } // Add a new element at the specified index @Override public void add (int index, E e) { // Doubles array, if not big enough ensureCapacity(); // Move the elements to the right after the specified index for (int i = size - 1; i >= index; i--) { data[i + 1] = data[i]; } // Insert new element to data[index] and increase size
  • 29. data[index] = e; size++; } // Create a new larger array, double the current size + 1 private void ensureCapacity() { if (size >= data.length) { E[] newData = (E[]) (new Comparable[size * 2 + 1]); System.arraycopy (data, 0, newData, 0, size); data = newData; } } // Return true if this list contains the element @Override public boolean contains (E e) { for (int i = 0; i < size; i++) { if (e.equals(data[i])) { return true; } } return false; } // Return the element at the specified index @Override public E get (int index) { checkIndex (index); return data[index]; } // Throws IndexOutOfBoundsException, if needed private void checkIndex (int index) {
  • 30. if (index < 0 || index >= size) { throw new IndexOutOfBoundsException ("Index: " + index + ", Size: " + size); } } // Return the index of the first matching element // Return -1 if no match. @Override public int indexOf(E e) { for (int i = 0; i < size; i++) { if (e.equals (data[i])) { return i; } } return -1; } // Return the index of the last matching element // Return -1 if no match. @Override public int lastIndexOf (E e) { for (int i = size - 1; i >= 0; i--) { if (e.equals (data[i])) { return i; } } return -1; } // Remove the element at the specified position // Shift any subsequent elements to the left.
  • 31. // Return the element that was removed from the list. @Override public E remove(int index) { checkIndex (index); E old = data[index]; // Shift data to the left for (int j = index; j < size - 1; j++) { data[j] = data[j + 1]; } data[size - 1] = null; // This element is now null size--; // Decrement size return old; } // Replace the element at the specified position // with the specified element. @Override public E set (int index, E e) { checkIndex (index); E old = data[index]; data[index] = e; return old; } // Return a string representation of the array @Override public String toString() { StringBuilder result = new StringBuilder("["); for (int i = 0; i < size; i++) { result.append (data[i]); if (i < size - 1) { result.append (", ");
  • 32. } } return result.toString() + "]"; } // Trims the capacity of the array to the current size // If size == capacity, no need to trim public void trimToSize() { if (size != data.length) { E[] newData = (E[]) (new Comparable[size]); System.arraycopy (data, 0, newData, 0, size); data = newData; } } // Clear the array: create a new empty one @Override public void clear() { data = (E[]) new Comparable[INITIAL_CAPACITY]; size = 0; } // Override iterator() defined in Iterable @Override public java.util.Iterator iterator() { return new ArrayListIterator(); } // Private iterator class for myArrayList class private class ArrayListIterator implements java.util.Iterator { private int current = 0; // Current index // Return true when there are more elements past current @Override public boolean hasNext() {
  • 33. return(current < size); } // Return the element at current @Override public E next() { return data[current++]; } // Remove the element at current @Override public void remove() { MyArrayList.this.remove(current); } } } MyLinkedList.java :- ------------------------------------ public class MyLinkedList extends MyAbstractList implements Comparable { private Node head, tail; // head and tail pointers // Create a default list public MyLinkedList() { } // Need this for implementing Comparable public int compareTo (MyLinkedList e) { return(size() - e.size()); } // Create a list from an array of objects public MyLinkedList (E[] objects) { super(objects); // Passes the array up to abstract parent }
  • 34. // Return the head element in the list public E getFirst() { if (size == 0) { return null; } else { return head.element; } } // Return the last element in the list public E getLast() { if (size == 0) { return null; } else { return tail.element; } } // Add an element to the beginning of the list public void addFirst (E e) { // Create a new node for element e Node newNode = new Node(e); newNode.next = head; // link the new node with the head head = newNode; // head points to the new node size++; // Increase list size if (tail == null) // new node is only node { tail = head; }
  • 35. } // Add an element to the end of the list public void addLast (E e) { // Create a new node for element e Node newNode = new Node(e); if (tail == null) { head = tail = newNode; // new node is only node } else { tail.next = newNode; // Link the new with the last node tail = tail.next; // tail now points to the last node } size++; // Increase size } // Remove the head node and // return the object from the removed node public E removeFirst() { if (size == 0) { return null; } else { Node temp = head; head = head.next; size--; if (head == null) { tail = null; } return temp.element; }
  • 36. } // Remove the last node and return the object from it public E removeLast() { if (size == 0) { return null; } else if (size == 1) { Node temp = head; head = tail = null; size = 0; return temp.element; } else { Node current = head; for (int i = 0; i < size - 2; i++) { current = current.next; } Node temp = tail; tail = current; tail.next = null; size--; return temp.element; } } // Remove the element at the specified position // Return the element that was removed from the list. @Override public E remove (int index) { if (index < 0 || index >= size) {
  • 37. return null; } else if (index == 0) { return removeFirst(); } else if (index == size - 1) { return removeLast(); } else { Node previous = head; for (int i = 1; i < index; i++) { previous = previous.next; } Node current = previous.next; previous.next = current.next; size--; return current.element; } } // Return a String representation of the linked list elements @Override public String toString() { StringBuilder result = new StringBuilder("["); Node current = head; for (int i = 0; i < size; i++) { result.append (current.element); current = current.next; if (current != null) { result.append (", "); // Separate elements with a comma
  • 38. } else { result.append ("]"); // Insert the ] in the string } } return result.toString(); } // Clear the list @Override public void clear() { size = 0; head = tail = null; } @Override // Add a new element at specified index in this list public void add(int index, E e) { if (index == 0) { addFirst (e); } else if (index == size) { addLast (e); } else { checkIndex (index); // Create a new node for element e Node newNode = new Node(e); Node previous = head; for (int i = 1; i < index; i++) { previous = previous.next;
  • 39. } newNode.next = previous.next; previous.next = newNode; size++; // Increase size } } // Return true if this list contains the element e @Override public boolean contains(E e) { Node current = head; for (int i = 0; i < size; i++) { if (current.element == e) { return true; } current = current.next; } return false; } // Return the element at the specified index @Override public E get (int index) { if (index < 0 || index >= size) { return null; } else { Node current = head; for (int i = 0; i == index; i++) { current = current.next; }
  • 40. return current.element; } } // Return the index of the first matching element // Return -1 if no match @Override public int indexOf (E e) { Node current = head; for (int i = 0; i < size; i++) { if (current.element.equals(e)) { return i; } current = current.next; } return -1; } // Return the index of the last matching element // Return -1 if no match. @Override public int lastIndexOf (E e) { int lastIndex = -1; Node current = head; for (int i = 0; i < size; i++) { if (e.equals (current.element)) { lastIndex = i; } current = current.next; } return lastIndex; }
  • 41. // Replace the element at the specified position // with the specified element @Override public E set (int index, E e) { Node current = head; for (int i = 0; i < index; i++) { current = current.next; } E old = current.element; current.element = e; return old; } // Override iterator() defined in Iterable @Override public java.util.Iterator iterator() { return new LinkedListIterator(); } // Throws IndexOutOfBoundsException, if needed private void checkIndex (int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException ("Index: " + index + ", Size: " + size); } } // The Node class private class Node { E element; Node next; public Node (E element) {
  • 42. this.element = element; } } // Private iterator class for myArrayList class private class LinkedListIterator implements java.util.Iterator { private Node current = head; // Current index @Override public boolean hasNext() { return(current != null); } @Override public E next() { E e = current.element; current = current.next; return e; } @Override public void remove() { MyLinkedList.this.remove (current.element); } } @Override public int compareTo(E o) { // TODO Auto-generated method stub return 0; } } MyQueue.java :- ----------------------------- public class MyQueue { private MyLinkedList list = new MyLinkedList();
  • 43. public void enqueue(E e) { list.addLast(e); } public E dequeue() { return (E) list.removeFirst(); } public int getSize() { return list.size(); } @Override public String toString() { return "Queue: " + list.toString(); } } MyStack.java :- ------------------------ public class MyStack implements Comparable { private MyArrayList list = new MyArrayList(); // Use this to find top of stack and to compare Stacks public int getSize() { return list.size(); } // Look at top of stack, without removing it public E peek() { return (E)list.get (getSize() - 1); } // Place a new element on the stack public void push (E e) {
  • 44. list.add (e); } // Remove the top element from the stack public E pop() { E e = (E)list.get (getSize() - 1); list.remove (getSize() - 1); return e; } public boolean isEmpty() { return list.isEmpty(); } public int compareTo (MyStack e) { return(getSize() - e.getSize()); } public MyArrayList getList() { return list; } @Override public String toString() { return "Stack: " + list.toString(); } @Override public int compareTo(E o) { // TODO Auto-generated method stub return 0; } }