SlideShare a Scribd company logo
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

Similar to ReversePoem.java ---------------------------------- public cl.pdf

6_Array.pptx
6_Array.pptx6_Array.pptx
6_Array.pptx
shafat6712
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
freddysarabia1
 
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docxNew folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
curwenmichaela
 
Write a program to find the number of comparisons using the binary se.docx
 Write a program to find the number of comparisons using the binary se.docx Write a program to find the number of comparisons using the binary se.docx
Write a program to find the number of comparisons using the binary se.docx
ajoy21
 
Using NetBeansImplement a queue named QueueLL using a Linked List .pdf
Using NetBeansImplement a queue named QueueLL using a Linked List .pdfUsing NetBeansImplement a queue named QueueLL using a Linked List .pdf
Using NetBeansImplement a queue named QueueLL using a Linked List .pdf
siennatimbok52331
 
Collection and framework
Collection and frameworkCollection and framework
Collection and framework
SARAVANAN GOPALAKRISHNAN
 
Here is what I got so far, I dont know how to write union, interse.pdf
Here is what I got so far, I dont know how to write union, interse.pdfHere is what I got so far, I dont know how to write union, interse.pdf
Here is what I got so far, I dont know how to write union, interse.pdf
arihantpatna
 
I need help creating a parametized JUnit test case for the following.pdf
I need help creating a parametized JUnit test case for the following.pdfI need help creating a parametized JUnit test case for the following.pdf
I need help creating a parametized JUnit test case for the following.pdf
fonecomp
 
OrderTest.javapublic class OrderTest {       Get an arra.pdf
OrderTest.javapublic class OrderTest {         Get an arra.pdfOrderTest.javapublic class OrderTest {         Get an arra.pdf
OrderTest.javapublic class OrderTest {       Get an arra.pdf
akkhan101
 
import java-util--- public class MyLinkedList{ public static void.pdf
import java-util---  public class MyLinkedList{    public static void.pdfimport java-util---  public class MyLinkedList{    public static void.pdf
import java-util--- public class MyLinkedList{ public static void.pdf
asarudheen07
 
Everything needs to be according to the instructions- thank you! SUPPO.pdf
Everything needs to be according to the instructions- thank you! SUPPO.pdfEverything needs to be according to the instructions- thank you! SUPPO.pdf
Everything needs to be according to the instructions- thank you! SUPPO.pdf
firstchoiceajmer
 
STAGE 2 The Methods 65 points Implement all the methods t.pdf
STAGE 2 The Methods 65 points Implement all the methods t.pdfSTAGE 2 The Methods 65 points Implement all the methods t.pdf
STAGE 2 The Methods 65 points Implement all the methods t.pdf
babitasingh698417
 
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
arshin9
 
File LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdfFile LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdf
Conint29
 
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
davidwarner122
 
For each task, submit your source java code file.(1) Objective Im.pdf
For each task, submit your source java code file.(1) Objective Im.pdfFor each task, submit your source java code file.(1) Objective Im.pdf
For each task, submit your source java code file.(1) Objective Im.pdf
dhavalbl38
 
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdfHere is the editable codeSolutionimport java.util.NoSuchEleme.pdf
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
arrowmobile
 
So I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdfSo I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdf
aksahnan
 
Java Foundations StackADT-java --- - Defines the interface to a stack.docx
Java Foundations StackADT-java ---  - Defines the interface to a stack.docxJava Foundations StackADT-java ---  - Defines the interface to a stack.docx
Java Foundations StackADT-java --- - Defines the interface to a stack.docx
VictorXUQGloverl
 
Implement the additional 5 methods as indicated in the LinkedList fi.pdf
Implement the additional 5 methods as indicated in the LinkedList fi.pdfImplement the additional 5 methods as indicated in the LinkedList fi.pdf
Implement the additional 5 methods as indicated in the LinkedList fi.pdf
footstatus
 

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

6_Array.pptx
6_Array.pptx6_Array.pptx
6_Array.pptx
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
 
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docxNew folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
 
Write a program to find the number of comparisons using the binary se.docx
 Write a program to find the number of comparisons using the binary se.docx Write a program to find the number of comparisons using the binary se.docx
Write a program to find the number of comparisons using the binary se.docx
 
Using NetBeansImplement a queue named QueueLL using a Linked List .pdf
Using NetBeansImplement a queue named QueueLL using a Linked List .pdfUsing NetBeansImplement a queue named QueueLL using a Linked List .pdf
Using NetBeansImplement a queue named QueueLL using a Linked List .pdf
 
Collection and framework
Collection and frameworkCollection and framework
Collection and framework
 
Here is what I got so far, I dont know how to write union, interse.pdf
Here is what I got so far, I dont know how to write union, interse.pdfHere is what I got so far, I dont know how to write union, interse.pdf
Here is what I got so far, I dont know how to write union, interse.pdf
 
I need help creating a parametized JUnit test case for the following.pdf
I need help creating a parametized JUnit test case for the following.pdfI need help creating a parametized JUnit test case for the following.pdf
I need help creating a parametized JUnit test case for the following.pdf
 
OrderTest.javapublic class OrderTest {       Get an arra.pdf
OrderTest.javapublic class OrderTest {         Get an arra.pdfOrderTest.javapublic class OrderTest {         Get an arra.pdf
OrderTest.javapublic class OrderTest {       Get an arra.pdf
 
import java-util--- public class MyLinkedList{ public static void.pdf
import java-util---  public class MyLinkedList{    public static void.pdfimport java-util---  public class MyLinkedList{    public static void.pdf
import java-util--- public class MyLinkedList{ public static void.pdf
 
Everything needs to be according to the instructions- thank you! SUPPO.pdf
Everything needs to be according to the instructions- thank you! SUPPO.pdfEverything needs to be according to the instructions- thank you! SUPPO.pdf
Everything needs to be according to the instructions- thank you! SUPPO.pdf
 
STAGE 2 The Methods 65 points Implement all the methods t.pdf
STAGE 2 The Methods 65 points Implement all the methods t.pdfSTAGE 2 The Methods 65 points Implement all the methods t.pdf
STAGE 2 The Methods 65 points Implement all the methods t.pdf
 
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
 
File LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdfFile LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdf
 
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
 
For each task, submit your source java code file.(1) Objective Im.pdf
For each task, submit your source java code file.(1) Objective Im.pdfFor each task, submit your source java code file.(1) Objective Im.pdf
For each task, submit your source java code file.(1) Objective Im.pdf
 
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdfHere is the editable codeSolutionimport java.util.NoSuchEleme.pdf
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
 
So I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdfSo I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdf
 
Java Foundations StackADT-java --- - Defines the interface to a stack.docx
Java Foundations StackADT-java ---  - Defines the interface to a stack.docxJava Foundations StackADT-java ---  - Defines the interface to a stack.docx
Java Foundations StackADT-java --- - Defines the interface to a stack.docx
 
Implement the additional 5 methods as indicated in the LinkedList fi.pdf
Implement the additional 5 methods as indicated in the LinkedList fi.pdfImplement the additional 5 methods as indicated in the LinkedList fi.pdf
Implement the additional 5 methods as indicated in the LinkedList fi.pdf
 

More from ravikapoorindia

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

More from ravikapoorindia (20)

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

Recently uploaded

Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
PedroFerreira53928
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
GeoBlogs
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
rosedainty
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
Fundacja Rozwoju Społeczeństwa Przedsiębiorczego
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
Vivekanand Anglo Vedic Academy
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
Celine George
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
PedroFerreira53928
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 

Recently uploaded (20)

Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 

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; } }