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
MyS.
Hi,I have added the methods and main class as per your requirement.pdfannaelctronics
Hi,
I have added the methods and main class as per your requirement. it is working fine now.
Highlighted the code changes.
MyLinkedListTest.java
public class MyLinkedListTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyLinkedList list = new MyLinkedList();
list.addFirst(\"AAAAA\");
list.add(\"1\");
list.add(\"2\");
list.add(\"3\");
list.addLast(\"ZZZZZ\");
System.out.println(\"Linked List Elements : \"+list.toString());
System.out.println(\"First element: \"+list.getFirst());
System.out.println(\"Second element: \"+list.getLast());
System.out.println(\"Removed First Element: \"+list.removeFirst());
System.out.println(\"Now Linked List Elements : \"+list.toString());
System.out.println(\"Removed Last Element: \"+list.removeLast());
System.out.println(\"Now Linked List Elements : \"+list.toString());
System.out.println(\"Removed all element: \");
list.removeAll();
System.out.println(\"Now Linked List Elements : \"+list.toString());
}
}
MyLinkedList.java
public class MyLinkedList extends MyAbstractList {
private Node head, tail;
/** Create a default list */
public MyLinkedList() {
}
/** Create a list from an array of objects */
public MyLinkedList(E[] objects) {
super(objects);
}
/** Return the head element in the list */
public E getFirst() {
if (size == 0) {
return null;
}
else {
return (E)head.element;
}
}
/** Return the last element in the list */
public E getLast() {
if (size == 0) {
return null;
}
else {
return (E)tail.element;
}
}
/** Add an element to the beginning of the list */
public void addFirst(E e) {
Node newNode = new Node(e); // Create a new node
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) // the new node is the only node in list
tail = head;
}
/** Add an element to the end of the list */
public void addLast(E e) {
Node newNode = new Node(e); // Create a new for element e
if (tail == null) {
head = tail = newNode; // The new node is the only node in list
}
else {
tail.next = newNode; // Link the new with the last node
tail = tail.next; // tail now points to the last node
}
size++; // Increase size
}
/** Add a new element at the specified index in this list
* The index of the head element is 0 */
public void add(int index, E e) {
if (index == 0) {
addFirst(e);
}
else if (index >= size) {
addLast(e);
}
else {
Node current = head;
for (int i = 1; i < index; i++) {
current = current.next;
}
Node temp = current.next;
current.next = new Node(e);
(current.next).next = temp;
size++;
}
}
/** Remove the head node and
* return the object that is contained in 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 (E)temp.element;
}
}
/** Remove all elements from list */
public void removeAll() {
while(true) {
if (size == 0) {
break;
}
else {
Node temp = head;
head =.
1- The design of a singly-linked list below is a picture of the functi (1).pdfafgt2012
1. The design of a singly-linked list
below is a picture of the function that needs to be used
below is the code of the above picture:
#include <string>
#include <iostream>
#include <cmath>
#include <cstdio>
#include <algorithm>
using namespace std;
#define defaultSize 100
void Assert(bool val, string s)
{
if (!val)
{ // Assertion failed -- close the program
cout << "Assertion Failed: " << s << endl;
exit(-1);
}
}
template <typename E>
class Link {
public:
E element; // Value for this node
Link *next; // Pointer to next node in list
// Constructors
Link(const E& elemval, Link<E>* nextval = NULL)
{ element = elemval; next = nextval; }
Link(Link<E>* nextval =NULL) { next = nextval; }
};
template <typename E>
class LList: public Link<E> {
private:
Link<E>* head;// Intialization helper method
Link<E>* tail;// Pointer to last element
Link<E>* curr;// Access to current element
int cnt;// Size of list
void init(){// Intialization helper method
curr = tail = head = new Link<E>;
cnt = 0;
}
void removeall() {// Return link nodes to free store
while(head != NULL) {
curr = head;
head = head->next;
delete curr;
}
}
public:
LList(int size=defaultSize) { init(); }// Constructor
~LList() { removeall(); }// Destructor
void print() const;// Print list contents
void clear() { removeall(); init(); }// Clear list
// Insert "it" at current position
void insert(const E& it) {
curr->next = new Link<E>(it, curr->next);
if (tail == curr) tail = curr->next; // New tail
cnt++;
}
void append(const E& it) { // Append "it" to list
tail = tail->next = new Link<E>(it, NULL);
cnt++;
}
// Remove and return current element
E remove() {
Assert(curr->next != NULL, "No element");
E it = curr->next->element; // Remember value
Link<E>* ltemp = curr->next; // Remember link node
if (tail == curr->next) tail = curr; // Reset tail
curr->next = curr->next->next; // Remove from list
delete ltemp; // Reclaim space
cnt--; // Decrement the count
return it;
}
void moveToStart()// Place curr at list start
{ curr = head; }
void moveToEnd() // Place curr at list end
{ curr = tail; }
void prev(){
if (curr == head) return;
Link<E>* temp = head;
while (temp->next!=curr) temp=temp->next;
curr = temp;
}
void next(){ if (curr != tail) curr = curr->next; }
int length() const { return cnt; }
int currPos() const {
Link<E>* temp = head;
int i;
for (i=0; curr != temp; i++)
temp = temp->next;
return i;
}
void moveToPos(int pos){
Assert ((pos>=0)&&(pos<=cnt), "Position out of range");
curr = head;
for(int i=0; i<pos; i++) curr = curr->next;
}
const E& getValue() const {
Assert(curr->next != NULL, "No value");
return curr->next->element;
}
};
completed this code to fulfill the requirement below:
Write a function to insert an integer into a singly-linked list of elements arranged from largest to
smallest. Requires that elements remain ordered after insertion.
2. The design of array-based stack
below is a picture of the function that needs to be used
below is the code of the above picture:
#include <string.h>
#.
META-INF/MANIFEST.MF
Manifest-Version: 1.0
.classpath
PriorityQueue.classpublicsynchronizedclass PriorityQueue {
Heap q;
public void PriorityQueue(int, java.util.Comparator);
public Object peek();
public Object remove();
void add(Object);
boolean isEmpty();
public int size();
}
PriorityQueue.javaPriorityQueue.javaimport java.util.Comparator;
publicclassPriorityQueue<E>{
Heap q;
/**
*PriorityQueue initializes the queue.
*
* @param initialCapacity an int that is the heaps initial size.
* @param comparator the priority of various imputs.
*/
publicPriorityQueue(int initialCapacity,Comparator<?super E> comparator){
q=newHeap(initialCapacity,comparator);
}
/**
* Peek, returns the next item in the queue without removing it.
*
* If it is empty then null is returned.
* @return the next item in the queue.
*/
public E peek(){
if(q.size()==0){
returnnull;
}
return(E) q.findMax();
}
/**
* This removes the first item from the queue.
*
* It returns null if the queue is empty.
* @return the first item in the queue.
*/
public E remove(){
if(q.size()==0){
returnnull;
}
return(E) q.removeMax();
}
/**
* This adds item to the queue
* @param item that is added to the queue.
*/
void add(E item){
q.insert(item);
}
/**
* isEmpty returns if the queue is empty or not.
*
* @return boolean if the queue is empty or not.
*/
boolean isEmpty(){
if(q.size()!=0){
returnfalse;
}
returntrue;
}
/**
* size returns the size of the queue.
*
* @return int the size of the queue.
*/
publicint size(){
return q.size();
}
}
ArithmeticExpression.classpublicsynchronizedclass ArithmeticExpression {
BinaryTree t;
java.util.ArrayList list;
String equation;
void ArithmeticExpression(String) throws java.text.ParseException;
public String toString(BinaryTree);
public String toPostfixString(BinaryTree);
void setVariable(String, int) throws java.rmi.NotBoundException;
public int evaluate(BinaryTree);
}
ArithmeticExpression.javaArithmeticExpression.javaimport java.rmi.NotBoundException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Stack;
/**
* ArithmeticExpression takes equations in the form of strings creates a binary
* tree, and can return either the regular or postfix equation. It also allows
* them to be calculated.
*
*
* Extra Credit:
* ** it can handle spaces or no spaces in the string inputted. ** it can return
* regular or postfix notation
*
* @author tai-lanhirabayashi
*
*/
publicclassArithmeticExpression{
BinaryTree t;
ArrayList list;
String equation;
/**
* ArithmeticExpression is the construction which takes in a space
* delimitated equation containing "*,/,+,-" symbols and converts it into a
* binary tree.
*
* If the expression is not valid it will throw a ParseException. This is ...
JAVA Demonstrate the use of your APL in a PartB_Driver class by doing.docxGavinUJtMathist
JAVA
Demonstrate the use of your APL in a PartB_Driver class by doing the following. Create a static method called removeConsecutiveDuplicates that removes any consecutive duplicate strings from an array positional list of Strings and returns the number of strings left after the removal. After calling the method, the positional list parameter should contain the same sequence of strings as before but with any consecutive duplicates removed. Illustrate your method using the following sets of strings and display the content of the list after executing the method.
NOTE: You MUST use a combination/variation of ALL the add and set methods (AddFirst, AddLast, AddBefore, AddAfter, and set) in creating one of the following original lists.
- harry ron tom tom tom hermione
- harry harry tom ron mary harry
- tom ron harry hermione mary
- mary mary tom james hermione hermione james harry harry harry
You MUST NOT use any other auxiliary data structure e.g., arrays in your implementation ofremoveConsecutiveDuplicates.
Sample Output (for last set of Strings)
Original positional list:
[0] mary [1] mary [2] tom [3] james [4] hermione [5] hermione [6] james [7] harry [8] harry [9] harry
APL.java
public class ArrayPositionalList<E> implements PositionalList<E> {
private static class ArrPos<E> implements Position<E> {
private int index;
private E element;
public ArrPos(E e, int i) {
index = i;
element = e;
}
public E getElement() throws IllegalStateException {
if (index == -1) {
throw new IllegalStateException("Position no longer valid");
}
return element;
}
public void setElement(E e) {
element = e;
}
public int getIndex() {
return index;
}
public void setIndex(int i) {
index = i;
}
}
public static final int CAPACITY = 16;
private ArrPos<E>[] data;
private int size = 0;
public ArrayPositionalList() {
this(CAPACITY);
}
public ArrayPositionalList(int capacity) {
data = (ArrPos<E>[]) new ArrPos[capacity];
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public Position first() {
if (!isEmpty())
return data[0];
return null;
}
@Override
public Position last() {
if (!isEmpty())
return data[size - 1];
return null;
}
@Override
public Position before(Position p) throws IllegalArgumentException {
if (p.getIndex() > 0 && p.getIndex() < size) {
return data[p.getIndex() - 1];
}
if (p.getIndex() == 0)
return null;
throw new IllegalArgumentException();
}
@Override
public Position after(Position p) throws IllegalArgumentException {
if (p.getIndex() >= 0 && p.getIndex() < size - 1) {
return data[p.getIndex() + 1];
}
if (p.getIndex() == size - 1)
return null;
throw new IllegalArgumentException();
}
@Override
public Position addFirst(E e) {
if (size < data.length) {
for (int i = size - 1; i >= 0; i--) {
data[i + 1] = data[i];
data[i + 1].setIndex(data[i + 1].getIndex() + 1);
}
data[0] = new ArrPos<E>(e, 0);
size++;
return data[0];
}
return null;
}
@Override
public Position addLast(E e) {
if (size < data.length) {
da.
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdfmallik3000
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD
OR REMOVE NAME. DO NOT HARD CODE NAME. AGAIN MAKE SURE THE
PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR REMOVE NAME. PLEASE
MAKE SURE THE CODE RUNS WITHOUT ANY ERRORS.
Write a class that maintains the scores for a game application. Implement the addition and
removal function to update the database. The gamescore.txt contains player’ name and score data
record fields separated by comma. For Removal function, uses the name field to select record to
remove the game score record.
Use the List.java, LList.java, Dlink.java, GameEntry.java and gamescore.txt found below
Read gamescore.txt to initialize the Linked list in sorted order by score.
Ask the user to add or remove users to update the sorted linked list.
Display “Name exist” when add an exist name to the list.
Display “Name does not exist” when remove a name not on the list.
List.java File:
/** Source code example for \"A Practical Introduction to Data
Structures and Algorithm Analysis, 3rd Edition (Java)\"
by Clifford A. Shaffer
Copyright 2008-2011 by Clifford A. Shaffer
*/
/** List ADT */
public interface List
{
/**
* Remove all contents from the list, so it is once again empty. Client is
* responsible for reclaiming storage used by the list elements.
*/
public void clear();
/**
* Insert an element at the current location. The client must ensure that
* the list\'s capacity is not exceeded.
*
* @param item
* The element to be inserted.
*/
public void insert(E item);
/**
* Append an element at the end of the list. The client must ensure that
* the list\'s capacity is not exceeded.
*
* @param item
* The element to be appended.
*/
public void append(E item);
/**
* Remove and return the current element.
*
* @return The element that was removed.
*/
public E remove();
/** Set the current position to the start of the list */
public void moveToStart();
/** Set the current position to the end of the list */
public void moveToEnd();
/**
* Move the current position one step left. No change if already at
* beginning.
*/
public void prev();
/**
* Move the current position one step right. No change if already at end.
*/
public void next();
/** @return The number of elements in the list. */
public int length();
/** @return The position of the current element. */
public int currPos();
/**
* Set current position.
*
* @param pos
* The position to make current.
*/
public void moveToPos(int pos);
/** @return The current element. */
public E getValue();
}
LList.java File:
/**
* Source code example for \"A Practical Introduction to Data Structures and
* Algorithm Analysis, 3rd Edition (Java)\" by Clifford A. Shaffer Copyright
* 2008-2011 by Clifford A. Shaffer
*/
// Doubly linked list implementation
class LList implements List
{
private DLink head; // Pointer to list header
private DLink tail; // Pointer to last element in list
protected DLink curr; // Pointer ahead of current element
int cnt; // Size of list
// Constructors
LList(int size)
{
th.
Given below is the completed implementation of MyLinkedList class. O.pdfinfo430661
Given below is the completed implementation of MyLinkedList class. Other classes are not
modified and remain same as in question - MyList, MyAbstractList, TestMyLinkedList.
The output of TestMyLinkedList is shown below. Please don\'t forget to rate the answer if it
helped. Thank you very much.
Since the MyList is not completely pasted in the question ... giving the complete class file below
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);
E remove(int index);
void clear();
E set(int index, E e);
}
MyLinkedList.java
public class MyLinkedList> extends MyAbstractList
implements Comparable>
{
private Node head, tail; // head and tail pointers
// Create a default list
public MyLinkedList()
{
}
public int size()
{
return size;
}
// 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;
tai.
Hi,I have added the methods and main class as per your requirement.pdfannaelctronics
Hi,
I have added the methods and main class as per your requirement. it is working fine now.
Highlighted the code changes.
MyLinkedListTest.java
public class MyLinkedListTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyLinkedList list = new MyLinkedList();
list.addFirst(\"AAAAA\");
list.add(\"1\");
list.add(\"2\");
list.add(\"3\");
list.addLast(\"ZZZZZ\");
System.out.println(\"Linked List Elements : \"+list.toString());
System.out.println(\"First element: \"+list.getFirst());
System.out.println(\"Second element: \"+list.getLast());
System.out.println(\"Removed First Element: \"+list.removeFirst());
System.out.println(\"Now Linked List Elements : \"+list.toString());
System.out.println(\"Removed Last Element: \"+list.removeLast());
System.out.println(\"Now Linked List Elements : \"+list.toString());
System.out.println(\"Removed all element: \");
list.removeAll();
System.out.println(\"Now Linked List Elements : \"+list.toString());
}
}
MyLinkedList.java
public class MyLinkedList extends MyAbstractList {
private Node head, tail;
/** Create a default list */
public MyLinkedList() {
}
/** Create a list from an array of objects */
public MyLinkedList(E[] objects) {
super(objects);
}
/** Return the head element in the list */
public E getFirst() {
if (size == 0) {
return null;
}
else {
return (E)head.element;
}
}
/** Return the last element in the list */
public E getLast() {
if (size == 0) {
return null;
}
else {
return (E)tail.element;
}
}
/** Add an element to the beginning of the list */
public void addFirst(E e) {
Node newNode = new Node(e); // Create a new node
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) // the new node is the only node in list
tail = head;
}
/** Add an element to the end of the list */
public void addLast(E e) {
Node newNode = new Node(e); // Create a new for element e
if (tail == null) {
head = tail = newNode; // The new node is the only node in list
}
else {
tail.next = newNode; // Link the new with the last node
tail = tail.next; // tail now points to the last node
}
size++; // Increase size
}
/** Add a new element at the specified index in this list
* The index of the head element is 0 */
public void add(int index, E e) {
if (index == 0) {
addFirst(e);
}
else if (index >= size) {
addLast(e);
}
else {
Node current = head;
for (int i = 1; i < index; i++) {
current = current.next;
}
Node temp = current.next;
current.next = new Node(e);
(current.next).next = temp;
size++;
}
}
/** Remove the head node and
* return the object that is contained in 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 (E)temp.element;
}
}
/** Remove all elements from list */
public void removeAll() {
while(true) {
if (size == 0) {
break;
}
else {
Node temp = head;
head =.
1- The design of a singly-linked list below is a picture of the functi (1).pdfafgt2012
1. The design of a singly-linked list
below is a picture of the function that needs to be used
below is the code of the above picture:
#include <string>
#include <iostream>
#include <cmath>
#include <cstdio>
#include <algorithm>
using namespace std;
#define defaultSize 100
void Assert(bool val, string s)
{
if (!val)
{ // Assertion failed -- close the program
cout << "Assertion Failed: " << s << endl;
exit(-1);
}
}
template <typename E>
class Link {
public:
E element; // Value for this node
Link *next; // Pointer to next node in list
// Constructors
Link(const E& elemval, Link<E>* nextval = NULL)
{ element = elemval; next = nextval; }
Link(Link<E>* nextval =NULL) { next = nextval; }
};
template <typename E>
class LList: public Link<E> {
private:
Link<E>* head;// Intialization helper method
Link<E>* tail;// Pointer to last element
Link<E>* curr;// Access to current element
int cnt;// Size of list
void init(){// Intialization helper method
curr = tail = head = new Link<E>;
cnt = 0;
}
void removeall() {// Return link nodes to free store
while(head != NULL) {
curr = head;
head = head->next;
delete curr;
}
}
public:
LList(int size=defaultSize) { init(); }// Constructor
~LList() { removeall(); }// Destructor
void print() const;// Print list contents
void clear() { removeall(); init(); }// Clear list
// Insert "it" at current position
void insert(const E& it) {
curr->next = new Link<E>(it, curr->next);
if (tail == curr) tail = curr->next; // New tail
cnt++;
}
void append(const E& it) { // Append "it" to list
tail = tail->next = new Link<E>(it, NULL);
cnt++;
}
// Remove and return current element
E remove() {
Assert(curr->next != NULL, "No element");
E it = curr->next->element; // Remember value
Link<E>* ltemp = curr->next; // Remember link node
if (tail == curr->next) tail = curr; // Reset tail
curr->next = curr->next->next; // Remove from list
delete ltemp; // Reclaim space
cnt--; // Decrement the count
return it;
}
void moveToStart()// Place curr at list start
{ curr = head; }
void moveToEnd() // Place curr at list end
{ curr = tail; }
void prev(){
if (curr == head) return;
Link<E>* temp = head;
while (temp->next!=curr) temp=temp->next;
curr = temp;
}
void next(){ if (curr != tail) curr = curr->next; }
int length() const { return cnt; }
int currPos() const {
Link<E>* temp = head;
int i;
for (i=0; curr != temp; i++)
temp = temp->next;
return i;
}
void moveToPos(int pos){
Assert ((pos>=0)&&(pos<=cnt), "Position out of range");
curr = head;
for(int i=0; i<pos; i++) curr = curr->next;
}
const E& getValue() const {
Assert(curr->next != NULL, "No value");
return curr->next->element;
}
};
completed this code to fulfill the requirement below:
Write a function to insert an integer into a singly-linked list of elements arranged from largest to
smallest. Requires that elements remain ordered after insertion.
2. The design of array-based stack
below is a picture of the function that needs to be used
below is the code of the above picture:
#include <string.h>
#.
META-INF/MANIFEST.MF
Manifest-Version: 1.0
.classpath
PriorityQueue.classpublicsynchronizedclass PriorityQueue {
Heap q;
public void PriorityQueue(int, java.util.Comparator);
public Object peek();
public Object remove();
void add(Object);
boolean isEmpty();
public int size();
}
PriorityQueue.javaPriorityQueue.javaimport java.util.Comparator;
publicclassPriorityQueue<E>{
Heap q;
/**
*PriorityQueue initializes the queue.
*
* @param initialCapacity an int that is the heaps initial size.
* @param comparator the priority of various imputs.
*/
publicPriorityQueue(int initialCapacity,Comparator<?super E> comparator){
q=newHeap(initialCapacity,comparator);
}
/**
* Peek, returns the next item in the queue without removing it.
*
* If it is empty then null is returned.
* @return the next item in the queue.
*/
public E peek(){
if(q.size()==0){
returnnull;
}
return(E) q.findMax();
}
/**
* This removes the first item from the queue.
*
* It returns null if the queue is empty.
* @return the first item in the queue.
*/
public E remove(){
if(q.size()==0){
returnnull;
}
return(E) q.removeMax();
}
/**
* This adds item to the queue
* @param item that is added to the queue.
*/
void add(E item){
q.insert(item);
}
/**
* isEmpty returns if the queue is empty or not.
*
* @return boolean if the queue is empty or not.
*/
boolean isEmpty(){
if(q.size()!=0){
returnfalse;
}
returntrue;
}
/**
* size returns the size of the queue.
*
* @return int the size of the queue.
*/
publicint size(){
return q.size();
}
}
ArithmeticExpression.classpublicsynchronizedclass ArithmeticExpression {
BinaryTree t;
java.util.ArrayList list;
String equation;
void ArithmeticExpression(String) throws java.text.ParseException;
public String toString(BinaryTree);
public String toPostfixString(BinaryTree);
void setVariable(String, int) throws java.rmi.NotBoundException;
public int evaluate(BinaryTree);
}
ArithmeticExpression.javaArithmeticExpression.javaimport java.rmi.NotBoundException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Stack;
/**
* ArithmeticExpression takes equations in the form of strings creates a binary
* tree, and can return either the regular or postfix equation. It also allows
* them to be calculated.
*
*
* Extra Credit:
* ** it can handle spaces or no spaces in the string inputted. ** it can return
* regular or postfix notation
*
* @author tai-lanhirabayashi
*
*/
publicclassArithmeticExpression{
BinaryTree t;
ArrayList list;
String equation;
/**
* ArithmeticExpression is the construction which takes in a space
* delimitated equation containing "*,/,+,-" symbols and converts it into a
* binary tree.
*
* If the expression is not valid it will throw a ParseException. This is ...
JAVA Demonstrate the use of your APL in a PartB_Driver class by doing.docxGavinUJtMathist
JAVA
Demonstrate the use of your APL in a PartB_Driver class by doing the following. Create a static method called removeConsecutiveDuplicates that removes any consecutive duplicate strings from an array positional list of Strings and returns the number of strings left after the removal. After calling the method, the positional list parameter should contain the same sequence of strings as before but with any consecutive duplicates removed. Illustrate your method using the following sets of strings and display the content of the list after executing the method.
NOTE: You MUST use a combination/variation of ALL the add and set methods (AddFirst, AddLast, AddBefore, AddAfter, and set) in creating one of the following original lists.
- harry ron tom tom tom hermione
- harry harry tom ron mary harry
- tom ron harry hermione mary
- mary mary tom james hermione hermione james harry harry harry
You MUST NOT use any other auxiliary data structure e.g., arrays in your implementation ofremoveConsecutiveDuplicates.
Sample Output (for last set of Strings)
Original positional list:
[0] mary [1] mary [2] tom [3] james [4] hermione [5] hermione [6] james [7] harry [8] harry [9] harry
APL.java
public class ArrayPositionalList<E> implements PositionalList<E> {
private static class ArrPos<E> implements Position<E> {
private int index;
private E element;
public ArrPos(E e, int i) {
index = i;
element = e;
}
public E getElement() throws IllegalStateException {
if (index == -1) {
throw new IllegalStateException("Position no longer valid");
}
return element;
}
public void setElement(E e) {
element = e;
}
public int getIndex() {
return index;
}
public void setIndex(int i) {
index = i;
}
}
public static final int CAPACITY = 16;
private ArrPos<E>[] data;
private int size = 0;
public ArrayPositionalList() {
this(CAPACITY);
}
public ArrayPositionalList(int capacity) {
data = (ArrPos<E>[]) new ArrPos[capacity];
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public Position first() {
if (!isEmpty())
return data[0];
return null;
}
@Override
public Position last() {
if (!isEmpty())
return data[size - 1];
return null;
}
@Override
public Position before(Position p) throws IllegalArgumentException {
if (p.getIndex() > 0 && p.getIndex() < size) {
return data[p.getIndex() - 1];
}
if (p.getIndex() == 0)
return null;
throw new IllegalArgumentException();
}
@Override
public Position after(Position p) throws IllegalArgumentException {
if (p.getIndex() >= 0 && p.getIndex() < size - 1) {
return data[p.getIndex() + 1];
}
if (p.getIndex() == size - 1)
return null;
throw new IllegalArgumentException();
}
@Override
public Position addFirst(E e) {
if (size < data.length) {
for (int i = size - 1; i >= 0; i--) {
data[i + 1] = data[i];
data[i + 1].setIndex(data[i + 1].getIndex() + 1);
}
data[0] = new ArrPos<E>(e, 0);
size++;
return data[0];
}
return null;
}
@Override
public Position addLast(E e) {
if (size < data.length) {
da.
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdfmallik3000
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD
OR REMOVE NAME. DO NOT HARD CODE NAME. AGAIN MAKE SURE THE
PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR REMOVE NAME. PLEASE
MAKE SURE THE CODE RUNS WITHOUT ANY ERRORS.
Write a class that maintains the scores for a game application. Implement the addition and
removal function to update the database. The gamescore.txt contains player’ name and score data
record fields separated by comma. For Removal function, uses the name field to select record to
remove the game score record.
Use the List.java, LList.java, Dlink.java, GameEntry.java and gamescore.txt found below
Read gamescore.txt to initialize the Linked list in sorted order by score.
Ask the user to add or remove users to update the sorted linked list.
Display “Name exist” when add an exist name to the list.
Display “Name does not exist” when remove a name not on the list.
List.java File:
/** Source code example for \"A Practical Introduction to Data
Structures and Algorithm Analysis, 3rd Edition (Java)\"
by Clifford A. Shaffer
Copyright 2008-2011 by Clifford A. Shaffer
*/
/** List ADT */
public interface List
{
/**
* Remove all contents from the list, so it is once again empty. Client is
* responsible for reclaiming storage used by the list elements.
*/
public void clear();
/**
* Insert an element at the current location. The client must ensure that
* the list\'s capacity is not exceeded.
*
* @param item
* The element to be inserted.
*/
public void insert(E item);
/**
* Append an element at the end of the list. The client must ensure that
* the list\'s capacity is not exceeded.
*
* @param item
* The element to be appended.
*/
public void append(E item);
/**
* Remove and return the current element.
*
* @return The element that was removed.
*/
public E remove();
/** Set the current position to the start of the list */
public void moveToStart();
/** Set the current position to the end of the list */
public void moveToEnd();
/**
* Move the current position one step left. No change if already at
* beginning.
*/
public void prev();
/**
* Move the current position one step right. No change if already at end.
*/
public void next();
/** @return The number of elements in the list. */
public int length();
/** @return The position of the current element. */
public int currPos();
/**
* Set current position.
*
* @param pos
* The position to make current.
*/
public void moveToPos(int pos);
/** @return The current element. */
public E getValue();
}
LList.java File:
/**
* Source code example for \"A Practical Introduction to Data Structures and
* Algorithm Analysis, 3rd Edition (Java)\" by Clifford A. Shaffer Copyright
* 2008-2011 by Clifford A. Shaffer
*/
// Doubly linked list implementation
class LList implements List
{
private DLink head; // Pointer to list header
private DLink tail; // Pointer to last element in list
protected DLink curr; // Pointer ahead of current element
int cnt; // Size of list
// Constructors
LList(int size)
{
th.
Given below is the completed implementation of MyLinkedList class. O.pdfinfo430661
Given below is the completed implementation of MyLinkedList class. Other classes are not
modified and remain same as in question - MyList, MyAbstractList, TestMyLinkedList.
The output of TestMyLinkedList is shown below. Please don\'t forget to rate the answer if it
helped. Thank you very much.
Since the MyList is not completely pasted in the question ... giving the complete class file below
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);
E remove(int index);
void clear();
E set(int index, E e);
}
MyLinkedList.java
public class MyLinkedList> extends MyAbstractList
implements Comparable>
{
private Node head, tail; // head and tail pointers
// Create a default list
public MyLinkedList()
{
}
public int size()
{
return size;
}
// 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;
tai.
Labprogram.java
LinkedList.java
import java.util.NoSuchElementException;
public class LinkedList {
private class Node {
private T data;
private Node next;
private Node prev;
public Node(T data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
private int length;
private Node first;
private Node last;
private Node iterator;
/**** CONSTRUCTORS ****/
public LinkedList() {
first = null;
last = null;
iterator = null;
length = 0;
}
/**
* Converts the given array into a LinkedList
*
* @param array the array of values to insert into this LinkedList
* @postcondition
*/
public LinkedList(T[] array) {
}
/**
* Instantiates a new LinkedList by copying another List
*
* @param original the LinkedList to copy
* @postcondition a new List object, which is an identical,
* but separate, copy of the LinkedList original
*/
public LinkedList(LinkedList original) {
}
public T getFirst() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
return first.data;
}
public T getLast() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
return last.data;
}
public T getIterator() throws NullPointerException {
if (iterator != null) {
return iterator.data;
} else {
throw new NullPointerException("Iterator is off the end opf the list.");
}
}
public int getLength() {
return length;
}
public boolean isEmpty() {
return length == 0;
}
public boolean offEnd() {
return iterator == null;
}
public void addFirst(T data) {
Node newNode = new Node(data);
if (isEmpty()) {
first = newNode;
last = newNode;
} else {
newNode.next = first;
first.prev = newNode;
first = newNode;
}
length++;
}
public void addLast(T data) {
Node newNode = new Node(data);
if (isEmpty()) {
first = newNode;
last = newNode;
} else {
last.next = newNode;
newNode.prev = last;
last = newNode;
}
length++;
}
public void addIterator(T data) throws NullPointerException {
if (offEnd()) {
throw new NullPointerException("addIterator Iterator is off end.");
}
if (iterator == last) {
addLast(data);
} else {
Node newNode = new Node(data);
Node next = iterator.next;
newNode.next = next;
newNode.prev = iterator;
iterator.next = newNode;
next.prev = newNode;
length++;
}
}
public void removeFirst() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
if (length == 1) {
first = null;
last = null;
iterator = null;
} else {
if (iterator == first) {
iterator = null;
}
first = first.next;
first.prev = null;
}
length--;
}
public void removeLast() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
if (length == 1) {
first = null;
last = null;
iterator = null;
} else {
if (iterator == last) {
iterator = null;
}
last = last.prev;
last.next = null;
}
length--;
}
public void removeIterator() throws NullPointerException {
if (offEnd()) {
throw new NullPointerException("Iterator is off the end opf the list.");
}
if (iterator .
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docxcurwenmichaela
New folder/jsjf/ArrayStack.classpackage jsjf;
publicsynchronizedclass ArrayStack implements StackADT {
privatestaticfinal int DEFAULT_CAPACITY = 100;
private int top;
private Object[] stack;
public void ArrayStack();
public void ArrayStack(int);
public void push(Object);
private void expandCapacity();
public Object pop() throws exceptions.EmptyCollectionException;
public Object peek() throws exceptions.EmptyCollectionException;
public int size();
public boolean isEmpty();
public String toString();
}
New folder/jsjf/ArrayStack.javaNew folder/jsjf/ArrayStack.javapackage jsjf;
import jsjf.exceptions.*;
import java.util.Arrays;
// -------------------------------------------------------
// Author: Yifu Wu
// Date: 03/10/16
// Source Name: ArrayStack<T>
// Due date: 03/10/16
// Description:
/**
* An array implementation of a stack in which the bottom of the
* stack is fixed at index 0.
*
* @author Java Foundations
* @version 4.0
*/
publicclassArrayStack<T>implementsStackADT<T>
{
privatefinalstaticint DEFAULT_CAPACITY =100;
privateint top;
private T[] stack;
/**
* Creates an empty stack using the default capacity.
*/
publicArrayStack()
{
this(DEFAULT_CAPACITY);
}
/**
* Creates an empty stack using the specified capacity.
* @param initialCapacity the initial size of the array
*/
publicArrayStack(int initialCapacity)
{
top =0;
stack =(T[])(newObject[initialCapacity]);
}
/**
* Adds the specified element to the top of this stack, expanding
* the capacity of the array if necessary.
* @param element generic element to be pushed onto stack
*/
publicvoid push(T element)
{
if(size()== stack.length)
expandCapacity();
stack[top]= element;
top++;
}
/**
* Creates a new array to store the contents of this stack with
* twice the capacity of the old one.
*/
privatevoid expandCapacity()
{
//stack = Arrays.copyOf(stack, stack.length * 2);
System.out.println("Expanding stack capacity\n");
T[] temp =(T[])(newObject[2*top]);
for(int i=0; i< top; i++)
temp[i]= stack[i];
stack = temp;
}
/**
* Removes the element at the top of this stack and returns a
* reference to it.
* @return element removed from top of stack
* @throws EmptyCollectionException if stack is empty
*/
public T pop()throwsEmptyCollectionException
{
if(isEmpty())
thrownewEmptyCollectionException("stack");
top--;
T result = stack[top];
stack[top]=null;
return result;
}
/**
* Returns a reference to the element at the top of this stack.
* The element is not removed from the stack.
* @return element on top of stack
* @throws EmptyCollectionException if stack is empty
*/
public T peek()throwsEmptyCollectionException
{
if(isEmpty())
thrownewEmptyCollectionException("stack");
return stack[top-1];
}
/**
* Returns the number of elements in ...
Using NetBeansImplement a queue named QueueLL using a Linked List .pdfsiennatimbok52331
Using NetBeans
Implement a queue named QueueLL using a Linked List (same as we did for the stack). This
implementation must be used in all the following problems.
Implement a queue QueueST using a stack (use StackLL).
Test your implementations in the main with examples.
Solution
Answer:-
import java.util.*;
/* Class Node */
class Node
{
protected int data;
protected Node link;
/* Constructor */
public Node()
{
link = null;
data = 0;
}
/* Constructor */
public Node(int d,Node n)
{
data = d;
link = n;
}
/* Function to set link to next Node */
public void setLink(Node n)
{
link = n;
}
/* Function to set data to current Node */
public void setData(int d)
{
data = d;
}
/* Function to get link to next node */
public Node getLink()
{
return link;
}
/* Function to get data from current Node */
public int getData()
{
return data;
}
}
/* Class linkedQueue */
class linkedQueue
{
protected Node front, rear;
public int size;
/* Constructor */
public linkedQueue()
{
front = null;
rear = null;
size = 0;
}
/* Function to check if queue is empty */
public boolean isEmpty()
{
return front == null;
}
/* Function to get the size of the queue */
public int getSize()
{
return size;
}
/* Function to insert an element to the queue */
public void insert(int data)
{
Node nptr = new Node(data, null);
if (rear == null)
{
front = nptr;
rear = nptr;
}
else
{
rear.setLink(nptr);
rear = rear.getLink();
}
size++ ;
}
/* Function to remove front element from the queue */
public int remove()
{
if (isEmpty() )
throw new NoSuchElementException(\"Underflow Exception\");
Node ptr = front;
front = ptr.getLink();
if (front == null)
rear = null;
size-- ;
return ptr.getData();
}
/* Function to check the front element of the queue */
public int peek()
{
if (isEmpty() )
throw new NoSuchElementException(\"Underflow Exception\");
return front.getData();
}
/* Function to display the status of the queue */
public void display()
{
System.out.print(\"\ Queue = \");
if (size == 0)
{
System.out.print(\"Empty\ \");
return ;
}
Node ptr = front;
while (ptr != rear.getLink() )
{
System.out.print(ptr.getData()+\" \");
ptr = ptr.getLink();
}
System.out.println();
}
}
/* Class LinkedQueueImplement */
public class LinkedQueueImplement
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
/* Creating object of class linkedQueue */
linkedQueue lq = new linkedQueue();
/* Perform Queue Operations */
System.out.println(\"Linked Queue Test\ \");
char ch;
do
{
System.out.println(\"\ Queue Operations\");
System.out.println(\"1. insert\");
System.out.println(\"2. remove\");
System.out.println(\"3. peek\");
System.out.println(\"4. check empty\");
System.out.println(\"5. size\");
int choice = scan.nextInt();
switch (choice)
{
case 1 :
System.out.println(\"Enter integer element to insert\");
lq.insert( scan.nextInt() );
break;
case 2 :
try
{
System.out.println(\"Removed Element = \"+ lq.remove());
}
catch (Exception e)
{
System.out.println(\"Error : \" + e.getMessage());
}
break;
case 3 .
Here is what I got so far, I dont know how to write union, interse.pdfarihantpatna
Gomez runs a small pottery firm. He hires one helper at $11,500 per year, pays annual rent of
$7,000 for his shop, and spends $22,500 per year on materials. He has $40,000 of his own funds
invested in equipment (pottery wheels, kilns, and so forth) that could earn him $6,500 per year if
alternatively invested. He has been offered $22,000 per year to work as a potter for a competitor.
He estimates his entrepreneurial talents are worth $4,500 per year (input cost for organizing
resources). Total annual revenue from pottery sales is $80,000. Calculate the accounting profit
and the economic profit for Gomez’s pottery firm.
Accounting Profit = $
Economic Profit = $
Solution
Let me first tell you what it is, so that you understand better -
In calculating economic profit, opportunity costs are deducted from revenues earned.
Opportunity costs are the alternative returns foregone by using the chosen inputs. As a result,
you can have a significant accounting profit with little to no economic profit.
For example, say you invest $100,000 to start a business, and in that year you earn $120,000 in
profits. Your accounting profit would be $20,000. However, say that same year you could have
earned an income of $45,000 had you been employed. Therefore, you have an economic loss of
$25,000 (120,000 - 100,000 - 45,000).Per AnnumHelper Salary11,500Shop Rent7000material
cost22500Gomez funds40000Alternate Investment income6,500Gomez goodwill
talent4500Annual Sales Revenue80000Annual Salary as potter22000Total Salary when working
as Potter22000+6500 = 28,500Total CostHelper Salary11,500Shop Rent7000Material
cost22500Gomez entrepreneurial talent450045,500Annual Sales Revenue80000Accounting
profit80,000 -45,500 = 34,500Economic Profit=34,500 -28,500=6000.
I need help creating a parametized JUnit test case for the following.pdffonecomp
I need help creating a parametized JUnit test case for the following class.
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import static java.lang.Integer.valueOf;
public class IntegerSet {
/**
* The only instance variable in the class. No other variables allowed.
*/
private List list;
public int size() {
return list.size();
}
public boolean isEmpty() {
return list.isEmpty();
}
/**
* Initializes the empty set.
*/
public IntegerSet() {
list = new LinkedList();
}
/**
* Initializes a set with the numbers in the argument.
*/
public IntegerSet(Integer[] integers) {
this();
if (integers == null) {
throw new NullPointerException(\"The argument cannot be null\");
} else {
for (Integer i : integers) {
if (!exists(i)) {
this.insertElement(i);
}
}
}
Collections.sort(list);
}
/**
* Inserts an integer to the set if the integer does not exist in the set
*/
public void insertElement(int i) {
if (!list.contains(i)) {
list.add(i);
}
}
/**
* Inserts to the set all the integers in the argument which do not exist in
* the set.
*/
public void insertAll(Integer[] data) {
if (data == null) {
throw new NullPointerException(\"The argument cannot be null\");
// throw new
// IllegalArgumentException(\"The argument cannot be null\");
} else {
Arrays.sort(data);
for (Integer num : data) {
if (!exists(num)) {
insertElement(num);
}
}
}
}
/**
* Deletes an integer from the set if it exists in the set.
*/
public void deleteElement(int i) {
list.remove(i);
}
/**
* Deletes all the elements in the set.
*/
public void deleteAll() {
list.clear();
}
/**
* Returns true if the argument exists in the set, false otherwise.
*/
public boolean exists(int i) {
return list.contains(i);
}
public String toString() {
char delimiter = \' \';
String str = \"[\";
for (Integer i : list) {
str += i;
str += delimiter;
}
return str + \"]\";
}
/**
* Finds the union of two sets. A null pointer is considered an empty set.
*
* Return \"new IntegerSet()\" when the result is an empty set.
*/
public static IntegerSet union(IntegerSet set1, IntegerSet set2) {
IntegerSet union = new IntegerSet();
if (set1.isEmpty() && set2.isEmpty()) {
return union;
}
if (!set1.list.isEmpty()) {
for (Integer num : set1.list) {
if (!union.list.contains(num)) {
union.list.add(num);
}
}
}
if (!set2.isEmpty()) {
for (Integer num : set2.list) {
if (!union.list.contains(num)) {
union.list.add(num);
}
}
}
return union;
}
/**
* Finds the intersection of two sets. A null pointer is considered an empty
* set.
*
* Return \"new IntegerSet()\" when the result is an empty set.
*/
public static IntegerSet intersection(IntegerSet set1, IntegerSet set2) {
IntegerSet intersection = new IntegerSet();
// check for null pointers
if (set1.list.isEmpty() || set2.list.isEmpty()) {
return intersection;
}
for (Integer num : set1.list) {
if ((!intersection.list.contains(num)) && set2.list.contains(num)) {
intersection.list.add(num);
}
}
return intersection;
}
/**
* Builds an array with the ele.
OrderTest.javapublic class OrderTest { Get an arra.pdfakkhan101
OrderTest.java
public class OrderTest {
/**
* Get an array of specified size and pass it to Order.order().
* Report the results.
*/
public static void main(String[] args) {
if (args.length != 1) {//1
System.out.println(\"Usage: java OrderTest sizeOfArray\ \"
+ \"\\tor\ \\tjava OrderTest arrayFile\");
System.exit(1);
}
// create or read the int[]
int size = 0;
int[] array = new int[0];//5
try {
size = Integer.parseInt(args[0]);
array = ArrayOfInts.randomizedArray(size);
} catch (NumberFormatException nfe) {//8
try {
array = ArrayOfInts.arrayFromFile(args[0]);
size = array.length;
} catch (Exception e) {
System.err.println(\"unable to read array from \" + args[0]);
System.exit(1);//14
}
}
System.out.println(\"before:\");//15
for (int i = 0; i < array.length; i++) {//2 n
System.out.printf(((i+1) % 10 > 0) ? \" %d\" : \" %d\ \", array[i]);//1
}
int myNum = Order.order(array); //this is the call we want to measure
System.out.println(\"\ after:\");//18
for (int i = 0; i < array.length; i++) {//2 n
System.out.printf(((i+1) % 10 > 0) ? \" %d\" : \" %d\ \", array[i]);
}
System.out.println(myNum);
}
}
ArrayOfInts.java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ArrayOfInts {
/**
* Returns an array of consecutive ints from 1 to size.
*/
public static int[] orderedArray(int size) {
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = i+1;
}
return a;
}
/**
* Returns a randomized array containing ints from 1 to size.
*/
public static int[] randomizedArray(int size) {
ArrayList aL = new ArrayList();
for (int i = 0; i < size; i++) {
aL.add(i+1);
}
Collections.shuffle(aL);
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = aL.get(i);
}
return a;
}
/**
* Writes an int[] to a plain-text file with ints separated by spaces.
* Useful for creating input files for repeatable tests.
*/
public static void arrayToFile(int[] array, String outfile) {
try {
FileWriter fw = new FileWriter(outfile);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outFile = new PrintWriter(bw);
for (int i : array) {
outFile.print(i + \" \");
}
outFile.close();
} catch (IOException e) {
System.err.println(\"Could not write to \" + outfile + \"\ \" + e);
}
}
/**
* Read ints from a file and return them in an int[]
*/
public static int[] arrayFromFile(String infile) throws FileNotFoundException,
InputMismatchException {
Scanner scan = new Scanner(new File(infile));
ArrayList aL = new ArrayList();
while (scan.hasNext()) {
aL.add(scan.nextInt());
}
scan.close();
int[] a = new int[aL.size()];
for (int i = 0; i < a.length; i++) {
a[i] = aL.get(i);
}
return a;
}
}
Order.java
public class Order {
/**
* Take an int[] and reorganize it so they are in ascending order.
*/
public static int order(int[] array) .
import java-util--- public class MyLinkedList{ public static void.pdfasarudheen07
import java.util.*; public class MyLinkedList{ public static void main(String[] args){ } } //copy
MyList to here interface MyList extends Collection { /* MyList will inherite all methods from
Collection public boolean add(E e); public boolean addAll(Collection extends E> c); public void
clear(); public boolean contains(Object o); public boolean containsAll(Collection> c); public
boolean isEmpty(); public boolean remove(Object o); public boolean removeAll(Collection> c);
public boolean retainAll(Collection> c); public int size(); public Object[] toArray(); public T[]
toArray(T[] arr); */ //abstract method public void add(int index, E e); public E get(int index);
public int indexOf(Object e); public int lastIndexOf(E e); public E remove(int index); public E
set(int index, E e); //default method @Override public default boolean add(E e){ add(size(), e);
return true; } @Override public default boolean isEmpty(){ return size()==0; } @Override
public default boolean remove(Object e){ if(indexOf(e) >= 0){ remove(indexOf(e)); return true;
} else{ return false; } } @Override public default boolean containsAll(Collection> c){
for(Object e : c){ if(!contains(e)){ return false; } } return true; } @Override public default
boolean addAll( Collection extends E> c){ for(E e : c){ add(e); } return true; } /* removeAll:
this[1,1,2,3] c[1,2,4] this.removeAll(c) [3] */ @Override public default boolean removeAll(
Collection> c){ for(Object e : c){ while(contains(e)){ this.remove(e); } } return true; } /*
retainAll this[1,1,2,3] c[1,2,4] this.retainAll(c) [1,1,2] */ @Override public default boolean
retainAll( Collection> c){ for(E e : this){ if(!c.contains(e)){ this.remove(e); } } return true; }
@Override public default Object[] toArray(){ Object[] results = new Object[size()]; int i = 0;
for(E e : this){ results[i++] = e; } return results; } /* T[] array */ @Override public default T[]
toArray(T[] array){ int i = 0; for(E e : this){ array[i++] = (T)e; } return array; } } class
TwoWayLinkedList implements MyList { //inner static class Node public class Node { E
element; Node next; Node previous; public Node(E e){ element = e; } } private Node head, tail;
private int size = 0; public TwoWayLinkedList(){ /* head = null; tail = null; size = 0; */ } public
TwoWayLinkedList(E[] objects){ } public E getFirst(){ return null; } public E getLast(){ return
null; } public void addFirst(E e){ } public void addLast(E e){ } public E removeFirst(){ return
null; } public E removeLast(){ return null; } @Override public void add(int index, E e){ }
@Override public E remove(int index){ return null; } @Override public void clear(){ }
@Override public boolean contains(Object e){ return false; } @Override public E get(int index){
return null; } @Override public int indexOf(Object e){ return -1; } @Override public int
lastIndexOf(Object e){ return -1; } @Override public E set(int index, E e){ return null; }
@Override public int size(){ return size; } //toString() @Override public String.
Everything needs to be according to the instructions- thank you! SUPPO.pdffirstchoiceajmer
Everything needs to be according to the instructions, thank you!
SUPPORTING CODE:
MyList.java
/**
This interface specifies the basic operations of any list-like object.
This interface contains a variation of the methods of the
standard java.util.List interface.
*/
public interface MyList {
/**
Adds an element at the end of the list.
*/
public void addToEnd(Object o);
/**
Inserts an element at the specified index
Throws NoSuchElementException if index is out of bounds.
*/
public void insertAt(int index, Object o);
/**
Removes the element at the specified index
Throws NoSuchElementException if index is out of bounds.
*/
public void removeAt(int index);
/**
Returns the element at the specified index
Throws NoSuchElementException if index is out of bounds.
*/
public Object getAt(int index);
/**
Returns the size of the list.
@return the number of elements in the list
*/
public int getSize();
/**
Returns a list iterator for this list.
@return a list iterator for this list
*/
public MyListIterator getIterator();
}
MyListIterator.java
/**
A list iterator allows access of a position in a list.
This interface contains a subset of the methods of the
standard java.util.ListIterator interface. The methods for
backward traversal are not included.
*/
public interface MyListIterator
{
/**
Moves the iterator past the next element.
@return the traversed element
*/
Object next();
/**
Tests if there is an element after the iterator
position.
@return true if there is an element after the iterator
position
*/
boolean hasNext();
}
Main.java
// you may use this file to write and run code to test your MyArrayList class
public class Main {
public static void main(String[] args) {
}
}
FILE THAT NEEDS THAT NEEDS CODE:
MyArrayList.java
// Complete the implementation of your MyArrayList class in this file
public class MyArrayList implements MyList {
// Implement the required fields and methods here
private int capacity = 8;
private Object[ ] array = new Object [capacity];
private int size = 0;
@Override
public void add(Object o) {
if (size >= capacity){
Object[] temp = new Object[2*array.length];
for(int i=0;i<size;++i){
temp[i] = array[i];
}
this.capacity = 2*array.length;
array = temp;
array[size++] = o;
return;
}
else
{
array[size++] = o;
}
}
@Override
public int size() {
return size;
}
@Override
public Object at(int index) {
if (index >= capacity)
return null;
else
return array[index];
}
@Override
public void insertAt(int index, Object o) {
if (index >= capacity)
return;
else
{
size++;
for (int x = size - 1; x > index; x--) {
array[x] = array[x - 1];
}
array[index] = o;
}
}
@Override
public void removeAt(int index) {
if (index >= size || size == 0)
return;
else {
Object e = array[index];
for (int x = index; x < this.array.length - 1; x++) {
array[x] = array[x + 1];
}
size--;
}
}
public void ensureCapacity(int minCapacity) {
}
public void trimToSize() {
ensureCapacity(size);
}
// Do not alter the code below
@Override
public MyListIterator getIterator() {
return new MyA.
STAGE 2 The Methods 65 points Implement all the methods t.pdfbabitasingh698417
STAGE 2: The Methods (65 points) Implement all the methods that are marked as Left as
Exercise. The Driver program only works when you have done all the methods. I have added the
template of all the methods with a placeholder value as return types of the methods. For example,
return 0 if method returns an int value.
List of the methods left as exercise are as follows: /** Create a list from an array of objects */
@SuppressWarnings("unchecked") public MyLinkedList(E[] objects) /** Add a new element at the
specified index in this list in ascending order */ public void addInOrder(E e) /** Check to see if this
list contains element e */ public boolean contains(E e) /** Remove all the occurrences of the
element e * from this list. Return true if the element is * removed. */ public boolean removeAll(E e)
/** Remove the first occurrence of the element e * from this list. Return true if the element is *
removed. */ public boolean remove(E e) /** Return the element at the specified index */ public E
get(int index) /** Return the index of the head matching element in * this list. Return -1 if no match.
*/ public int indexOf(Object e) /** Return the index of the last matching element in * this list. Return
-1 if no match. */ public int lastIndexOf(E e) /** Replace the element at the specified position * in
this list with the specified element. */ public E set(int index, E e) /** Print this list using recursion */
public void printList() /** Returns an array containing all of the elements * in this collection; * the
runtime type of the returned array is that of * the specified array. */ public <E> E[] toArray(E[]
array) /** Split the original list in half. The original * list will continue to reference the * front half of
the original list and the method * returns a reference to a new list that stores the * back half of the
original list.
public class MyLinkedList<E extends Comparable<E>> {
private Node<E> head, tail;
private int size = 0; // Number of elements in the list
public MyLinkedList() {
head=tail=null;
size=0;
}
/** 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) {
Node<E> newNode = new Node<>(e); // Create a new node
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) // the new node is the only node in list
tail = head;
}
/** Add an element to the end of the list */
public void addLast(E e) {
Node<E> newNode = new Node<>(e); // Create a new for element e
if (tail == null) {
head = tail = newNode; // The new node is the only node in list
}
else {
tail.next = newNode; // Link the new with the last node
tail = newNode; // tail now points to the last node
}
size++; // Incr.
2.(Sorted list array implementation)This sorted list ADT discussed .pdfarshin9
2.(Sorted list: array implementation)This sorted list ADT discussed in class should be extended
by the addition of two new methods:
//Interface: ArrayListADT
//works for int
public interface ArrayListADT {
public boolean isEmpty(); //Method to determine whether the list is empty.
public boolean isFull(); //Method to determine whether the list is full.
public int listSize(); //Method to return the number of elements in the list.
public int maxListSize(); //Method to return the maximum size of the list.
public void print(); //Method to output the elements of the list.
public boolean isItemAtEqual(int location, int item); //Method to determine whether item is
the same as the item in the list at location.
public void insertAt(int location, int insertItem); //Method to insert insertItem in the list at
the position
public void insertEnd(int insertItem); //Method to insert insertItem at the end of the list.
public void removeAt(int location); //Method to remove the item from the list at location.
public int retrieveAt(int location); //Method to retrieve the element from the list at location.
public void replaceAt(int location, int repItem); //Method to replace the element in the list at
location with repItem.
public void clearList(); //Method to remove all the elements from the list.
public int search(int searchItem); //Method to determine whether searchItem is in the list.
public void remove(int removeItem); //Method to remove an item from the list.
}
//Class: ArrayListClass implements
//Interface: ArrayListADT
public abstract class ArrayListClass implements ArrayListADT {
protected int length; //to store the length of the list
protected int maxSize; //to store the maximum size of the list
protected int[] list; //array to hold the list elements
//Default constructor
public ArrayListClass() {
maxSize = 100;
length = 0;
list = new int[maxSize];
}
//Alternate Constructor
public ArrayListClass(int size) {
if(size <= 0) {
System.err.println(\"The array size must be positive. Creating an array of size 100.\");
maxSize = 100;
}
else
maxSize = size;
length = 0;
list = new int[maxSize];
}
public boolean isEmpty() {
return (length == 0);
}
public boolean isFull() {
return (length == maxSize);
}
public int listSize() {
return length;
}
public int maxListSize() {
return maxSize;
}
public void print() {
for (int i = 0; i < length; i++)
System.out.print(list[i] + \" \");
System.out.println();
}
public boolean isItemAtEqual(int location, int item) {
if (location < 0 || location >= length) {
System.err.println(\"The location of the item to be compared is out of range.\");
return false;
}
return list[location]== item;
}
public void clearList() {
for (int i = 0; i < length; i++)
list[i] = 0;
length = 0;
System.gc(); //invoke the Java garbage collector
}
public void removeAt(int location) {
if (location < 0 || location >= length)
System.err.println(\"The location of the item to be removed is out of range.\");
else {
for(int i = location; i < length - 1; i++)
list[i] .
File LinkedList.java Defines a doubly-l.pdfConint29
File: LinkedList.java
/**
* Defines a doubly-linked list class
*/
import java.util.NoSuchElementException;
public class LinkedList {
private class Node {
private T data;
private Node next;
private Node prev;
public Node(T data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
private int length;
private Node first;
private Node last;
private Node iterator;
/**** CONSTRUCTORS ****/
/**
* Instantiates a new LinkedList with default values
* @postcondition
*/
public LinkedList() {
}
/**
* Converts the given array into a LinkedList
* @param array the array of values to insert into this LinkedList
* @postcondition
*/
public LinkedList(T[] array) {
}
/**
* Instantiates a new LinkedList by copying another List
* @param original the LinkedList to copy
* @postcondition a new List object, which is an identical,
* but separate, copy of the LinkedList original
*/
public LinkedList(LinkedList original) {
}
/**** ACCESSORS ****/
/**
* Returns the value stored in the first node
* @precondition
* @return the value stored at node first
* @throws NoSuchElementException
*/
public T getFirst() throws NoSuchElementException {
return null;
}
/**
* Returns the value stored in the last node
* @precondition
* @return the value stored in the node last
* @throws NoSuchElementException
*/
public T getLast() throws NoSuchElementException {
return null;
}
/**
* Returns the data stored in the iterator node
* @precondition
* @return the data stored in the iterator node
* @throw NullPointerException
*/
public T getIterator() throws NullPointerException {
return null;
}
/**
* Returns the current length of the LinkedList
* @return the length of the LinkedList from 0 to n
*/
public int getLength() {
return -1;
}
/**
* Returns whether the LinkedList is currently empty
* @return whether the LinkedList is empty
*/
public boolean isEmpty() {
return false;
}
/**
* Returns whether the iterator is offEnd, i.e. null
* @return whether the iterator is null
*/
public boolean offEnd() {
return false;
}
/**** MUTATORS ****/
/**
* Creates a new first element
* @param data the data to insert at the front of the LinkedList
* @postcondition
*/
public void addFirst(T data) {
return;
}
/**
* Creates a new last element
* @param data the data to insert at the end of the LinkedList
* @postcondition
*/
public void addLast(T data) {
return;
}
/**
* Inserts a new element after the iterator
* @param data the data to insert
* @precondition
* @throws NullPointerException
*/
public void addIterator(T data) throws NullPointerException{
return;
}
/**
* removes the element at the front of the LinkedList
* @precondition
* @postcondition
* @throws NoSuchElementException
*/
public void removeFirst() throws NoSuchElementException {
return;
}
/**
* removes the element at the end of the LinkedList
* @precondition
* @postcondition
* @throws NoSuchElementException
*/
public void removeLast() throws NoSuchElementException {
return;
}
/**
* removes the element referenced by the iterator
* @precondition
* @pos.
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...davidwarner122
FOR MORE CLASSES VISIT
www.tutorialoutlet.com
Below is a given ArrayList class and Main class in search algorithms. Please modify the existing program so it can time the sequential search and the binary search methods several times each for randomly generated values, and record the results in a table. Do not time individual searches, but groups of them. For example, time 100 searches together or 1,000 searches together. Compare the running times of these two search methods that are obtained during the experiment.
For each task, submit your source java code file.(1) Objective Im.pdfdhavalbl38
For each task, submit your source java code file.
(1) Objective: Implement Link List
Write a class that maintains the scores for a game application. Implement the addition and
removal function to update the database. The gamescore.txt contains player’ name and score data
record fields separated by comma. For Removal function, uses the name field to select record to
remove the game score record.
Download – List.java, LList.java, Dlink.java, GameEntry.java, gamescore.txt
(a)Read gamescore.txt to initialize the Linked list in sorted order. (1 point)
(b)Provide Remove and Add function for user to update the sorted linked list. (1 point)
(2)Add a reverse function to the LList.java class to reverse the order of the linked list. (2 points).
---------------------------------------------------------------------------------------------------------------------
-----------------------------------------
//gamescore.txt
Mike,1105
Rob,750
Paul,720
Anna,660
Rose,590
Jack,510
--------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------
//DLink.java
/** Source code example for \"A Practical Introduction to Data
Structures and Algorithm Analysis, 3rd Edition (Java)\"
by Clifford A. Shaffer
Copyright 2008-2011 by Clifford A. Shaffer
*/
/** Doubly linked list node */
class DLink {
private E element; // Value for this node
private DLink next; // Pointer to next node in list
private DLink prev; // Pointer to previous node
/** Constructors */
DLink(E it, DLink p, DLink n)
{ element = it; prev = p; next = n; }
DLink(DLink p, DLink n) { prev = p; next = n; }
/** Get and set methods for the data members */
DLink next() { return next; }
DLink setNext(DLink nextval)
{ return next = nextval; }
DLink prev() { return prev; }
DLink setPrev(DLink prevval)
{ return prev = prevval; }
E element() { return element; }
E setElement(E it) { return element = it; }
}
--------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------
//GameEntry.java
public class GameEntry {
protected String name;
protected int score;
public GameEntry(String n, int s) {
name = n;
score = s;
}
public String getName() {return name;}
public int getScore() {return score;}
public String toString() {
return \"(\"+name+\",\"+score+\")\";
}
}
--------------------------------------------------------------------------------------------------------------------
----------------------------------
//List.java
/** Source code example for \"A Practical Introduction to Data
Structures and Algorithm Analysis, 3rd Edition (Java)\"
by Clifford A. Shaffer
Copyright 2008-2011 by Clifford A. Shaffer
*/
/** List ADT */
public interface List {
/** Remove all contents from the list, so it is once again
empty. Client is responsible for reclaiming storage
used by the list elements. */
p.
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdfarrowmobile
Here is the editable code:
Solution
import java.util.NoSuchElementException;
public class DoublyLinkedListImpl {
private Node head;
private Node tail;
private int size;
public DoublyLinkedListImpl() {
size = 0;
}
private class Node {
E element;
Node next;
Node prev;
public Node(E element, Node next, Node prev) {
this.element = element;
this.next = next;
this.prev = prev;
}
}
public int size() { return size; }
public boolean isEmpty() { return size == 0; }
public void addFirst(E element) {
Node tmp = new Node(element, head, null);
if(head != null ) {head.prev = tmp;}
head = tmp;
if(tail == null) { tail = tmp;}
size++;
System.out.println(\"adding: \"+element);
}
/**
* adds element at the end of the linked list
* @param element
*/
public void addLast(E element) {
Node tmp = new Node(element, null, tail);
if(tail != null) {tail.next = tmp;}
tail = tmp;
if(head == null) { head = tmp;}
size++;
System.out.println(\"adding: \"+element);
}
public void iterateForward(){
System.out.println(\"iterating forward..\");
Node tmp = head;
while(tmp != null){
System.out.println(tmp.element);
tmp = tmp.next;
}
}
/**
* this method walks backward through the linked list
*/
public void iterateBackward(){
System.out.println(\"iterating backword..\");
Node tmp = tail;
while(tmp != null){
System.out.println(tmp.element);
tmp = tmp.prev;
}
}
public E removeFirst() {
if (size == 0) throw new NoSuchElementException();
Node tmp = head;
head = head.next;
head.prev = null;
size--;
System.out.println(\"deleted: \"+tmp.element);
return tmp.element;
}
public E removeLast() {
if (size == 0) throw new NoSuchElementException();
Node tmp = tail;
tail = tail.prev;
tail.next = null;
size--;
System.out.println(\"deleted: \"+tmp.element);
return tmp.element;
}
public static void main(String a[]){
DoublyLinkedListImpl dll = new DoublyLinkedListImpl();
dll.addFirst(10);
dll.addFirst(34);
dll.addLast(56);
dll.addLast(364);
dll.iterateForward();
dll.removeFirst();
dll.removeLast();
dll.iterateBackward();
}
}
import java.util.Scanner;
/* Class Node */
class Node
{
protected int data;
protected Node next, prev;
/* Constructor */
public Node()
{
next = null;
prev = null;
data = 0;
}
/* Constructor */
public Node(int d, Node n, Node p)
{
data = d;
next = n;
prev = p;
}
/* Function to set link to next node */
public void setLinkNext(Node n)
{
next = n;
}
/* Function to set link to previous node */
public void setLinkPrev(Node p)
{
prev = p;
}
/* Funtion to get link to next node */
public Node getLinkNext()
{
return next;
}
/* Function to get link to previous node */
public Node getLinkPrev()
{
return prev;
}
/* Function to set data to node */
public void setData(int d)
{
data = d;
}
/* Function to get data from node */
public int getData()
{
return data;
}
}
/* Class linkedList */
class linkedList
{
protected Node start;
protected Node end ;
public int size;
/* Constructor */
public linkedList()
{
start = null;
end = null;
size = 0;
}
/* Function to check if list is empty */
public boolean isE.
So I have this code(StackInAllSocks) and I implemented the method but.pdfaksahnan
So I have this code( StackInAllSocks ) and I implemented the method but I can't seem to figure
out why there isn't anything showing up on the console. It should pop,peek and push b using the
methods from the class called ArrayListTen . The ArrayListTen works fine and compiles the
tested code of Rigth# but for StackInAllSocks it doesn't complete at all. note that file
VodeDodeis not to be changed is just a Node storage area of the array list.
Did I implement the method on StackInAllSocks correctly? if so, should I not use the method
from the ArrayListTen .?
__________________________________________________________________________
: the code is : VodeDodeis
class VodeDode<T> {
private T data;
private VodeDode<T> next;
private VodeDode<T> prev;
public VodeDode(T data) {
this.data = data;
this.next = null;
this.prev = null;}
public T getData() {
return data;}
public void setData(T data) {
this.data = data;}
public VodeDode<T> getNext() {
return this.next;}
public void setNext(VodeDode<T> next) {
this.next = next;}
public VodeDode<T> getPrev() {
return this.prev;}
public void setPrev(VodeDode<T> prev) {
this.prev = prev;}
@Override
public String toString() {
return data.toString();}}
_________________________________________________________________________
CODE that works fine called ArrayListTen:
import java.util.Iterator;
public class ArrayListTen<T> implements Iterable<T> {
private VodeDode<T> head; //beginning of list
private VodeDode<T> tail; //end of list
private int size;
private VodeDode<T> new_item;
public ArrayListTen( ){
this.head = null;
this.tail = null;
this.size = 0;}
public int lenght() {
return size ;}
public T getBegin() {
if (this.head != null) {
return head.getData();}
else { return null;}}
public void addBegin(T value) {
VodeDode<T> newVodeDode =new VodeDode<T>(value);
if (this.head== null) {
head = newVodeDode;
tail =newVodeDode;}
else {VodeDode<T> temp = head;
head = newVodeDode;
head.setNext(temp);}
size++;}
public T removeBegin() {
if(this.head == null) {
return null;}
else {T current = head.getData();
if (tail == head) {
tail = null;
head = null;
} else {
head = head.getNext();
head.setPrev(null);}size--;
return current;}}
public T getEnd() {
if (tail != null) {
return tail.getData();
} else {
return null;}}
public void addEnd(T value) {
VodeDode<T> newVodeDode = new VodeDode<T>(value);
if (this.tail == null) {
head = newVodeDode;
tail = newVodeDode;
} else {
newVodeDode.setPrev(tail);
tail.setNext(newVodeDode);
tail = newVodeDode;}
size++;}
public T removeEnd() {
if(this.tail == null) {
return null;}
else {
T current = tail.getData();//was head.
if (head == tail) {
head = null;
tail = null;
} else {
tail = tail.getPrev();
tail.setNext(null);}
size--;
return current;}}
public T removeBN(T value) {
VodeDode<T> currVodeDode = head;
VodeDode<T> prevVodeDode = null;
while(currVodeDode != null){
if(currVodeDode.getData().equals(value)){
if(prevVodeDode != null){
prevVodeDode.setNext(currVodeDode.getNext());}
else{
head = curr.
Java Foundations StackADT-java --- - Defines the interface to a stack.docxVictorXUQGloverl
Java Foundations
StackADT.java
/**
* Defines the interface to a stack collection.
*
* @author Java Foundations
* @version 4.0
*/
public interface StackADT<T> {
/**
* Adds the specified element to the top of this stack.
*
* @param element element to be pushed onto the stack
*/
public void push(T element);
/**
* Removes and returns the top element from this stack.
*
* @return the element removed from the stack
* @throws EmptyCollectionException if the stack is empty
*/
public T pop();
/**
* Returns the top element of this stack without removing it from the stack.
*
* @return the element on top of the stack. It is not removed from the stack
* @throws EmptyCollectionException if the stack is empty
*/
public T peek();
/**
* Returns true if this stack contains no elements.
*
* @return true if the stack is empty, false if the stack is not empty
*/
public boolean isEmpty();
/**
* Returns the number of elements in this stack.
*
* @return the number of elements in the stack
*/
public int size();
}
QueueADT.java
/**
* QueueADT defines the interface to a queue collection.
*
* @author Java Foundation
* @version 4.0
*/
public interface QueueADT<T> {
/**
* Adds one element to the rear of this queue.
*
* @param element the element to be added to the rear of the queue
*/
public void enqueue(T element);
/**
* Removes and returns the element at the front of this queue.
*
* @return the element at the front of the queue
* @throws EmptyCollectionException if the queue is empty
*/
public T dequeue();
/**
* Returns without removing the element at the front of this queue.
*
* @return the first element in the queue
* @throws EmptyCollectionException if the queue is empty
*/
public T first();
/**
* Returns true if this queue contains no elements.
*
* @return true if the queue is empty, false if the queue is not empty
*/
public boolean isEmpty();
/**
* Returns the number of elements in this queue.
*
* @return the number of elements in the queue
*/
public int size();
}
LinkedDeque.java
public class LinkedDeque<T> implements QueueADT<T>, StackADT<T>, DequeADT<T> {
// inner class for a double linked list node
private class DNode<T> {
private T element;
private DNode<T> prev, next;
}
// data fields for the LinkedDeque class
private DNode<T> front, rear;
private int size;
// deque interface methods
@Override
public void addFirst(T element) {
// create a new node and set it up
DNode<T> newNode = new DNode<T>();
newNode.element = element; // from param to new node obj
newNode.prev = newNode.next = null;
if(this.isEmpty()) {
// we are making the only node in the deque
this.rear = this.front = newNode;
} else {
// there already exists a new node
// so, put the new node before the front node
newNode.next = this.front;
this.front.prev = newNode;
this.front = newNode;
}
this.size++;
}
@Override
public T removeFirst() {
T grabbedElt = this.getFirst(); // checks for empty for us
if.
1.The Excavata includes taxa that are photosynthetic, parasitic, sym.pdfravikapoorindia
1.The Excavata includes taxa that are photosynthetic, parasitic, symbiotic and heterotrophic.
Many of the taxa lack mitochondria, and, therefore, seemed to conform to the requirements of an
archaic premitochondrial ancestor of all eukaryotes. This theory, called the Archezoa
Hypothesis, was created by Cavalier-Smith (1983). The former archezoa began to find homes in
interesting and unexpected places. Patterson (1999) and Simpson and Patterson (2001) defined a
striking structural similarity that many of the former archezoan taxa possessed, a feeding groove
called an excavate. The excavate was a groove that ran longitudinally on the cell surface and was
associated with at least one recurrent flagellum, which set up currents in the groove that served
to concentrate suspended particles and move them to a cytostome. Simpson (2003) identified
seven such groups that had such an excavate apparatus: the Core Jakobids, Malawimonas,
Trimastix, Carpediemonas, Retortomonads, Diplomonads, and the Heterolobosids
(amoeboflagellates). Many of the excavate taxa were mitochondriate and had clear affinities
with taxa that did not bear an excavate. So, by 2003 (Simpson 2003 and Cavalier-Smith 2003b)
at least 10 groups (we interpret it as 11 groups) had been identified as excavate taxa (see Table
1). Burki et al. (2008) and Hampl et al. (2009) confirmed the monophyly of the excavates by
phylogenomic analyses relative to members of the other supergroups. Furthermore, the excavates
appear to be a very deep-rooting group, equivalent to the unikonts (Opisthokonta), and the
bikonts (Chromalveolata + Rhizaria + Archaeplastida).
2.It is very difficult to discover drug against TB sice the bacteria which is mycobacterium is
thermostabile and made up of mycolic acid . An increasing evidence of multidrug resistance in
TB is the major problem in developing drug against TB. The mycobacterium is able to
accumulate drug and become resistant to these drug. This bacteria develop allernative
mechanism to become resistant to the drug.
Malaria
some antimalarials can only be used in certain areas of the world because parasites are resistant
to some drugs. For example, chloroquine can only be used to prevent Plasmodium falciparum in
regions of South America because Plasmodium falciparum is completely resistant to chloroquine
in Africa and Asia.
E. ameoba histoilica
Solution
1.The Excavata includes taxa that are photosynthetic, parasitic, symbiotic and heterotrophic.
Many of the taxa lack mitochondria, and, therefore, seemed to conform to the requirements of an
archaic premitochondrial ancestor of all eukaryotes. This theory, called the Archezoa
Hypothesis, was created by Cavalier-Smith (1983). The former archezoa began to find homes in
interesting and unexpected places. Patterson (1999) and Simpson and Patterson (2001) defined a
striking structural similarity that many of the former archezoan taxa possessed, a feeding groove
called an excavate. The excavate was a groove that ran longit.
1. According to morphological species concept focus on external phys.pdfravikapoorindia
1. According to morphological species concept focus on external physical characters such as
size, shape, color structure of the organism .
2. Biological species concept explains why the members of species are resemble to one another.
When two organisms are breeded their genes pass into their combined offspring.
3. Phylogenetic species concept defines a species as a group having a shared and unique
evolotionary history. The offsprings in the concept are parental pattern of ancestry and descent.
4. Unified species concept achieved by treating existing as separately and secondary species
criteria as different line of evidence.
5. From the above quenstion species XL and XXL are showing variation in their morphology and
their number of chromosome. The remaining species show variation in the colour of shell.
6. From the above infromation the correct answer is option \"e\" all the above.
Solution
1. According to morphological species concept focus on external physical characters such as
size, shape, color structure of the organism .
2. Biological species concept explains why the members of species are resemble to one another.
When two organisms are breeded their genes pass into their combined offspring.
3. Phylogenetic species concept defines a species as a group having a shared and unique
evolotionary history. The offsprings in the concept are parental pattern of ancestry and descent.
4. Unified species concept achieved by treating existing as separately and secondary species
criteria as different line of evidence.
5. From the above quenstion species XL and XXL are showing variation in their morphology and
their number of chromosome. The remaining species show variation in the colour of shell.
6. From the above infromation the correct answer is option \"e\" all the above..
More Related Content
Similar to ReversePoem.java ---------------------------------- public cl.pdf
Labprogram.java
LinkedList.java
import java.util.NoSuchElementException;
public class LinkedList {
private class Node {
private T data;
private Node next;
private Node prev;
public Node(T data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
private int length;
private Node first;
private Node last;
private Node iterator;
/**** CONSTRUCTORS ****/
public LinkedList() {
first = null;
last = null;
iterator = null;
length = 0;
}
/**
* Converts the given array into a LinkedList
*
* @param array the array of values to insert into this LinkedList
* @postcondition
*/
public LinkedList(T[] array) {
}
/**
* Instantiates a new LinkedList by copying another List
*
* @param original the LinkedList to copy
* @postcondition a new List object, which is an identical,
* but separate, copy of the LinkedList original
*/
public LinkedList(LinkedList original) {
}
public T getFirst() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
return first.data;
}
public T getLast() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
return last.data;
}
public T getIterator() throws NullPointerException {
if (iterator != null) {
return iterator.data;
} else {
throw new NullPointerException("Iterator is off the end opf the list.");
}
}
public int getLength() {
return length;
}
public boolean isEmpty() {
return length == 0;
}
public boolean offEnd() {
return iterator == null;
}
public void addFirst(T data) {
Node newNode = new Node(data);
if (isEmpty()) {
first = newNode;
last = newNode;
} else {
newNode.next = first;
first.prev = newNode;
first = newNode;
}
length++;
}
public void addLast(T data) {
Node newNode = new Node(data);
if (isEmpty()) {
first = newNode;
last = newNode;
} else {
last.next = newNode;
newNode.prev = last;
last = newNode;
}
length++;
}
public void addIterator(T data) throws NullPointerException {
if (offEnd()) {
throw new NullPointerException("addIterator Iterator is off end.");
}
if (iterator == last) {
addLast(data);
} else {
Node newNode = new Node(data);
Node next = iterator.next;
newNode.next = next;
newNode.prev = iterator;
iterator.next = newNode;
next.prev = newNode;
length++;
}
}
public void removeFirst() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
if (length == 1) {
first = null;
last = null;
iterator = null;
} else {
if (iterator == first) {
iterator = null;
}
first = first.next;
first.prev = null;
}
length--;
}
public void removeLast() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
if (length == 1) {
first = null;
last = null;
iterator = null;
} else {
if (iterator == last) {
iterator = null;
}
last = last.prev;
last.next = null;
}
length--;
}
public void removeIterator() throws NullPointerException {
if (offEnd()) {
throw new NullPointerException("Iterator is off the end opf the list.");
}
if (iterator .
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docxcurwenmichaela
New folder/jsjf/ArrayStack.classpackage jsjf;
publicsynchronizedclass ArrayStack implements StackADT {
privatestaticfinal int DEFAULT_CAPACITY = 100;
private int top;
private Object[] stack;
public void ArrayStack();
public void ArrayStack(int);
public void push(Object);
private void expandCapacity();
public Object pop() throws exceptions.EmptyCollectionException;
public Object peek() throws exceptions.EmptyCollectionException;
public int size();
public boolean isEmpty();
public String toString();
}
New folder/jsjf/ArrayStack.javaNew folder/jsjf/ArrayStack.javapackage jsjf;
import jsjf.exceptions.*;
import java.util.Arrays;
// -------------------------------------------------------
// Author: Yifu Wu
// Date: 03/10/16
// Source Name: ArrayStack<T>
// Due date: 03/10/16
// Description:
/**
* An array implementation of a stack in which the bottom of the
* stack is fixed at index 0.
*
* @author Java Foundations
* @version 4.0
*/
publicclassArrayStack<T>implementsStackADT<T>
{
privatefinalstaticint DEFAULT_CAPACITY =100;
privateint top;
private T[] stack;
/**
* Creates an empty stack using the default capacity.
*/
publicArrayStack()
{
this(DEFAULT_CAPACITY);
}
/**
* Creates an empty stack using the specified capacity.
* @param initialCapacity the initial size of the array
*/
publicArrayStack(int initialCapacity)
{
top =0;
stack =(T[])(newObject[initialCapacity]);
}
/**
* Adds the specified element to the top of this stack, expanding
* the capacity of the array if necessary.
* @param element generic element to be pushed onto stack
*/
publicvoid push(T element)
{
if(size()== stack.length)
expandCapacity();
stack[top]= element;
top++;
}
/**
* Creates a new array to store the contents of this stack with
* twice the capacity of the old one.
*/
privatevoid expandCapacity()
{
//stack = Arrays.copyOf(stack, stack.length * 2);
System.out.println("Expanding stack capacity\n");
T[] temp =(T[])(newObject[2*top]);
for(int i=0; i< top; i++)
temp[i]= stack[i];
stack = temp;
}
/**
* Removes the element at the top of this stack and returns a
* reference to it.
* @return element removed from top of stack
* @throws EmptyCollectionException if stack is empty
*/
public T pop()throwsEmptyCollectionException
{
if(isEmpty())
thrownewEmptyCollectionException("stack");
top--;
T result = stack[top];
stack[top]=null;
return result;
}
/**
* Returns a reference to the element at the top of this stack.
* The element is not removed from the stack.
* @return element on top of stack
* @throws EmptyCollectionException if stack is empty
*/
public T peek()throwsEmptyCollectionException
{
if(isEmpty())
thrownewEmptyCollectionException("stack");
return stack[top-1];
}
/**
* Returns the number of elements in ...
Using NetBeansImplement a queue named QueueLL using a Linked List .pdfsiennatimbok52331
Using NetBeans
Implement a queue named QueueLL using a Linked List (same as we did for the stack). This
implementation must be used in all the following problems.
Implement a queue QueueST using a stack (use StackLL).
Test your implementations in the main with examples.
Solution
Answer:-
import java.util.*;
/* Class Node */
class Node
{
protected int data;
protected Node link;
/* Constructor */
public Node()
{
link = null;
data = 0;
}
/* Constructor */
public Node(int d,Node n)
{
data = d;
link = n;
}
/* Function to set link to next Node */
public void setLink(Node n)
{
link = n;
}
/* Function to set data to current Node */
public void setData(int d)
{
data = d;
}
/* Function to get link to next node */
public Node getLink()
{
return link;
}
/* Function to get data from current Node */
public int getData()
{
return data;
}
}
/* Class linkedQueue */
class linkedQueue
{
protected Node front, rear;
public int size;
/* Constructor */
public linkedQueue()
{
front = null;
rear = null;
size = 0;
}
/* Function to check if queue is empty */
public boolean isEmpty()
{
return front == null;
}
/* Function to get the size of the queue */
public int getSize()
{
return size;
}
/* Function to insert an element to the queue */
public void insert(int data)
{
Node nptr = new Node(data, null);
if (rear == null)
{
front = nptr;
rear = nptr;
}
else
{
rear.setLink(nptr);
rear = rear.getLink();
}
size++ ;
}
/* Function to remove front element from the queue */
public int remove()
{
if (isEmpty() )
throw new NoSuchElementException(\"Underflow Exception\");
Node ptr = front;
front = ptr.getLink();
if (front == null)
rear = null;
size-- ;
return ptr.getData();
}
/* Function to check the front element of the queue */
public int peek()
{
if (isEmpty() )
throw new NoSuchElementException(\"Underflow Exception\");
return front.getData();
}
/* Function to display the status of the queue */
public void display()
{
System.out.print(\"\ Queue = \");
if (size == 0)
{
System.out.print(\"Empty\ \");
return ;
}
Node ptr = front;
while (ptr != rear.getLink() )
{
System.out.print(ptr.getData()+\" \");
ptr = ptr.getLink();
}
System.out.println();
}
}
/* Class LinkedQueueImplement */
public class LinkedQueueImplement
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
/* Creating object of class linkedQueue */
linkedQueue lq = new linkedQueue();
/* Perform Queue Operations */
System.out.println(\"Linked Queue Test\ \");
char ch;
do
{
System.out.println(\"\ Queue Operations\");
System.out.println(\"1. insert\");
System.out.println(\"2. remove\");
System.out.println(\"3. peek\");
System.out.println(\"4. check empty\");
System.out.println(\"5. size\");
int choice = scan.nextInt();
switch (choice)
{
case 1 :
System.out.println(\"Enter integer element to insert\");
lq.insert( scan.nextInt() );
break;
case 2 :
try
{
System.out.println(\"Removed Element = \"+ lq.remove());
}
catch (Exception e)
{
System.out.println(\"Error : \" + e.getMessage());
}
break;
case 3 .
Here is what I got so far, I dont know how to write union, interse.pdfarihantpatna
Gomez runs a small pottery firm. He hires one helper at $11,500 per year, pays annual rent of
$7,000 for his shop, and spends $22,500 per year on materials. He has $40,000 of his own funds
invested in equipment (pottery wheels, kilns, and so forth) that could earn him $6,500 per year if
alternatively invested. He has been offered $22,000 per year to work as a potter for a competitor.
He estimates his entrepreneurial talents are worth $4,500 per year (input cost for organizing
resources). Total annual revenue from pottery sales is $80,000. Calculate the accounting profit
and the economic profit for Gomez’s pottery firm.
Accounting Profit = $
Economic Profit = $
Solution
Let me first tell you what it is, so that you understand better -
In calculating economic profit, opportunity costs are deducted from revenues earned.
Opportunity costs are the alternative returns foregone by using the chosen inputs. As a result,
you can have a significant accounting profit with little to no economic profit.
For example, say you invest $100,000 to start a business, and in that year you earn $120,000 in
profits. Your accounting profit would be $20,000. However, say that same year you could have
earned an income of $45,000 had you been employed. Therefore, you have an economic loss of
$25,000 (120,000 - 100,000 - 45,000).Per AnnumHelper Salary11,500Shop Rent7000material
cost22500Gomez funds40000Alternate Investment income6,500Gomez goodwill
talent4500Annual Sales Revenue80000Annual Salary as potter22000Total Salary when working
as Potter22000+6500 = 28,500Total CostHelper Salary11,500Shop Rent7000Material
cost22500Gomez entrepreneurial talent450045,500Annual Sales Revenue80000Accounting
profit80,000 -45,500 = 34,500Economic Profit=34,500 -28,500=6000.
I need help creating a parametized JUnit test case for the following.pdffonecomp
I need help creating a parametized JUnit test case for the following class.
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import static java.lang.Integer.valueOf;
public class IntegerSet {
/**
* The only instance variable in the class. No other variables allowed.
*/
private List list;
public int size() {
return list.size();
}
public boolean isEmpty() {
return list.isEmpty();
}
/**
* Initializes the empty set.
*/
public IntegerSet() {
list = new LinkedList();
}
/**
* Initializes a set with the numbers in the argument.
*/
public IntegerSet(Integer[] integers) {
this();
if (integers == null) {
throw new NullPointerException(\"The argument cannot be null\");
} else {
for (Integer i : integers) {
if (!exists(i)) {
this.insertElement(i);
}
}
}
Collections.sort(list);
}
/**
* Inserts an integer to the set if the integer does not exist in the set
*/
public void insertElement(int i) {
if (!list.contains(i)) {
list.add(i);
}
}
/**
* Inserts to the set all the integers in the argument which do not exist in
* the set.
*/
public void insertAll(Integer[] data) {
if (data == null) {
throw new NullPointerException(\"The argument cannot be null\");
// throw new
// IllegalArgumentException(\"The argument cannot be null\");
} else {
Arrays.sort(data);
for (Integer num : data) {
if (!exists(num)) {
insertElement(num);
}
}
}
}
/**
* Deletes an integer from the set if it exists in the set.
*/
public void deleteElement(int i) {
list.remove(i);
}
/**
* Deletes all the elements in the set.
*/
public void deleteAll() {
list.clear();
}
/**
* Returns true if the argument exists in the set, false otherwise.
*/
public boolean exists(int i) {
return list.contains(i);
}
public String toString() {
char delimiter = \' \';
String str = \"[\";
for (Integer i : list) {
str += i;
str += delimiter;
}
return str + \"]\";
}
/**
* Finds the union of two sets. A null pointer is considered an empty set.
*
* Return \"new IntegerSet()\" when the result is an empty set.
*/
public static IntegerSet union(IntegerSet set1, IntegerSet set2) {
IntegerSet union = new IntegerSet();
if (set1.isEmpty() && set2.isEmpty()) {
return union;
}
if (!set1.list.isEmpty()) {
for (Integer num : set1.list) {
if (!union.list.contains(num)) {
union.list.add(num);
}
}
}
if (!set2.isEmpty()) {
for (Integer num : set2.list) {
if (!union.list.contains(num)) {
union.list.add(num);
}
}
}
return union;
}
/**
* Finds the intersection of two sets. A null pointer is considered an empty
* set.
*
* Return \"new IntegerSet()\" when the result is an empty set.
*/
public static IntegerSet intersection(IntegerSet set1, IntegerSet set2) {
IntegerSet intersection = new IntegerSet();
// check for null pointers
if (set1.list.isEmpty() || set2.list.isEmpty()) {
return intersection;
}
for (Integer num : set1.list) {
if ((!intersection.list.contains(num)) && set2.list.contains(num)) {
intersection.list.add(num);
}
}
return intersection;
}
/**
* Builds an array with the ele.
OrderTest.javapublic class OrderTest { Get an arra.pdfakkhan101
OrderTest.java
public class OrderTest {
/**
* Get an array of specified size and pass it to Order.order().
* Report the results.
*/
public static void main(String[] args) {
if (args.length != 1) {//1
System.out.println(\"Usage: java OrderTest sizeOfArray\ \"
+ \"\\tor\ \\tjava OrderTest arrayFile\");
System.exit(1);
}
// create or read the int[]
int size = 0;
int[] array = new int[0];//5
try {
size = Integer.parseInt(args[0]);
array = ArrayOfInts.randomizedArray(size);
} catch (NumberFormatException nfe) {//8
try {
array = ArrayOfInts.arrayFromFile(args[0]);
size = array.length;
} catch (Exception e) {
System.err.println(\"unable to read array from \" + args[0]);
System.exit(1);//14
}
}
System.out.println(\"before:\");//15
for (int i = 0; i < array.length; i++) {//2 n
System.out.printf(((i+1) % 10 > 0) ? \" %d\" : \" %d\ \", array[i]);//1
}
int myNum = Order.order(array); //this is the call we want to measure
System.out.println(\"\ after:\");//18
for (int i = 0; i < array.length; i++) {//2 n
System.out.printf(((i+1) % 10 > 0) ? \" %d\" : \" %d\ \", array[i]);
}
System.out.println(myNum);
}
}
ArrayOfInts.java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ArrayOfInts {
/**
* Returns an array of consecutive ints from 1 to size.
*/
public static int[] orderedArray(int size) {
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = i+1;
}
return a;
}
/**
* Returns a randomized array containing ints from 1 to size.
*/
public static int[] randomizedArray(int size) {
ArrayList aL = new ArrayList();
for (int i = 0; i < size; i++) {
aL.add(i+1);
}
Collections.shuffle(aL);
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = aL.get(i);
}
return a;
}
/**
* Writes an int[] to a plain-text file with ints separated by spaces.
* Useful for creating input files for repeatable tests.
*/
public static void arrayToFile(int[] array, String outfile) {
try {
FileWriter fw = new FileWriter(outfile);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outFile = new PrintWriter(bw);
for (int i : array) {
outFile.print(i + \" \");
}
outFile.close();
} catch (IOException e) {
System.err.println(\"Could not write to \" + outfile + \"\ \" + e);
}
}
/**
* Read ints from a file and return them in an int[]
*/
public static int[] arrayFromFile(String infile) throws FileNotFoundException,
InputMismatchException {
Scanner scan = new Scanner(new File(infile));
ArrayList aL = new ArrayList();
while (scan.hasNext()) {
aL.add(scan.nextInt());
}
scan.close();
int[] a = new int[aL.size()];
for (int i = 0; i < a.length; i++) {
a[i] = aL.get(i);
}
return a;
}
}
Order.java
public class Order {
/**
* Take an int[] and reorganize it so they are in ascending order.
*/
public static int order(int[] array) .
import java-util--- public class MyLinkedList{ public static void.pdfasarudheen07
import java.util.*; public class MyLinkedList{ public static void main(String[] args){ } } //copy
MyList to here interface MyList extends Collection { /* MyList will inherite all methods from
Collection public boolean add(E e); public boolean addAll(Collection extends E> c); public void
clear(); public boolean contains(Object o); public boolean containsAll(Collection> c); public
boolean isEmpty(); public boolean remove(Object o); public boolean removeAll(Collection> c);
public boolean retainAll(Collection> c); public int size(); public Object[] toArray(); public T[]
toArray(T[] arr); */ //abstract method public void add(int index, E e); public E get(int index);
public int indexOf(Object e); public int lastIndexOf(E e); public E remove(int index); public E
set(int index, E e); //default method @Override public default boolean add(E e){ add(size(), e);
return true; } @Override public default boolean isEmpty(){ return size()==0; } @Override
public default boolean remove(Object e){ if(indexOf(e) >= 0){ remove(indexOf(e)); return true;
} else{ return false; } } @Override public default boolean containsAll(Collection> c){
for(Object e : c){ if(!contains(e)){ return false; } } return true; } @Override public default
boolean addAll( Collection extends E> c){ for(E e : c){ add(e); } return true; } /* removeAll:
this[1,1,2,3] c[1,2,4] this.removeAll(c) [3] */ @Override public default boolean removeAll(
Collection> c){ for(Object e : c){ while(contains(e)){ this.remove(e); } } return true; } /*
retainAll this[1,1,2,3] c[1,2,4] this.retainAll(c) [1,1,2] */ @Override public default boolean
retainAll( Collection> c){ for(E e : this){ if(!c.contains(e)){ this.remove(e); } } return true; }
@Override public default Object[] toArray(){ Object[] results = new Object[size()]; int i = 0;
for(E e : this){ results[i++] = e; } return results; } /* T[] array */ @Override public default T[]
toArray(T[] array){ int i = 0; for(E e : this){ array[i++] = (T)e; } return array; } } class
TwoWayLinkedList implements MyList { //inner static class Node public class Node { E
element; Node next; Node previous; public Node(E e){ element = e; } } private Node head, tail;
private int size = 0; public TwoWayLinkedList(){ /* head = null; tail = null; size = 0; */ } public
TwoWayLinkedList(E[] objects){ } public E getFirst(){ return null; } public E getLast(){ return
null; } public void addFirst(E e){ } public void addLast(E e){ } public E removeFirst(){ return
null; } public E removeLast(){ return null; } @Override public void add(int index, E e){ }
@Override public E remove(int index){ return null; } @Override public void clear(){ }
@Override public boolean contains(Object e){ return false; } @Override public E get(int index){
return null; } @Override public int indexOf(Object e){ return -1; } @Override public int
lastIndexOf(Object e){ return -1; } @Override public E set(int index, E e){ return null; }
@Override public int size(){ return size; } //toString() @Override public String.
Everything needs to be according to the instructions- thank you! SUPPO.pdffirstchoiceajmer
Everything needs to be according to the instructions, thank you!
SUPPORTING CODE:
MyList.java
/**
This interface specifies the basic operations of any list-like object.
This interface contains a variation of the methods of the
standard java.util.List interface.
*/
public interface MyList {
/**
Adds an element at the end of the list.
*/
public void addToEnd(Object o);
/**
Inserts an element at the specified index
Throws NoSuchElementException if index is out of bounds.
*/
public void insertAt(int index, Object o);
/**
Removes the element at the specified index
Throws NoSuchElementException if index is out of bounds.
*/
public void removeAt(int index);
/**
Returns the element at the specified index
Throws NoSuchElementException if index is out of bounds.
*/
public Object getAt(int index);
/**
Returns the size of the list.
@return the number of elements in the list
*/
public int getSize();
/**
Returns a list iterator for this list.
@return a list iterator for this list
*/
public MyListIterator getIterator();
}
MyListIterator.java
/**
A list iterator allows access of a position in a list.
This interface contains a subset of the methods of the
standard java.util.ListIterator interface. The methods for
backward traversal are not included.
*/
public interface MyListIterator
{
/**
Moves the iterator past the next element.
@return the traversed element
*/
Object next();
/**
Tests if there is an element after the iterator
position.
@return true if there is an element after the iterator
position
*/
boolean hasNext();
}
Main.java
// you may use this file to write and run code to test your MyArrayList class
public class Main {
public static void main(String[] args) {
}
}
FILE THAT NEEDS THAT NEEDS CODE:
MyArrayList.java
// Complete the implementation of your MyArrayList class in this file
public class MyArrayList implements MyList {
// Implement the required fields and methods here
private int capacity = 8;
private Object[ ] array = new Object [capacity];
private int size = 0;
@Override
public void add(Object o) {
if (size >= capacity){
Object[] temp = new Object[2*array.length];
for(int i=0;i<size;++i){
temp[i] = array[i];
}
this.capacity = 2*array.length;
array = temp;
array[size++] = o;
return;
}
else
{
array[size++] = o;
}
}
@Override
public int size() {
return size;
}
@Override
public Object at(int index) {
if (index >= capacity)
return null;
else
return array[index];
}
@Override
public void insertAt(int index, Object o) {
if (index >= capacity)
return;
else
{
size++;
for (int x = size - 1; x > index; x--) {
array[x] = array[x - 1];
}
array[index] = o;
}
}
@Override
public void removeAt(int index) {
if (index >= size || size == 0)
return;
else {
Object e = array[index];
for (int x = index; x < this.array.length - 1; x++) {
array[x] = array[x + 1];
}
size--;
}
}
public void ensureCapacity(int minCapacity) {
}
public void trimToSize() {
ensureCapacity(size);
}
// Do not alter the code below
@Override
public MyListIterator getIterator() {
return new MyA.
STAGE 2 The Methods 65 points Implement all the methods t.pdfbabitasingh698417
STAGE 2: The Methods (65 points) Implement all the methods that are marked as Left as
Exercise. The Driver program only works when you have done all the methods. I have added the
template of all the methods with a placeholder value as return types of the methods. For example,
return 0 if method returns an int value.
List of the methods left as exercise are as follows: /** Create a list from an array of objects */
@SuppressWarnings("unchecked") public MyLinkedList(E[] objects) /** Add a new element at the
specified index in this list in ascending order */ public void addInOrder(E e) /** Check to see if this
list contains element e */ public boolean contains(E e) /** Remove all the occurrences of the
element e * from this list. Return true if the element is * removed. */ public boolean removeAll(E e)
/** Remove the first occurrence of the element e * from this list. Return true if the element is *
removed. */ public boolean remove(E e) /** Return the element at the specified index */ public E
get(int index) /** Return the index of the head matching element in * this list. Return -1 if no match.
*/ public int indexOf(Object e) /** Return the index of the last matching element in * this list. Return
-1 if no match. */ public int lastIndexOf(E e) /** Replace the element at the specified position * in
this list with the specified element. */ public E set(int index, E e) /** Print this list using recursion */
public void printList() /** Returns an array containing all of the elements * in this collection; * the
runtime type of the returned array is that of * the specified array. */ public <E> E[] toArray(E[]
array) /** Split the original list in half. The original * list will continue to reference the * front half of
the original list and the method * returns a reference to a new list that stores the * back half of the
original list.
public class MyLinkedList<E extends Comparable<E>> {
private Node<E> head, tail;
private int size = 0; // Number of elements in the list
public MyLinkedList() {
head=tail=null;
size=0;
}
/** 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) {
Node<E> newNode = new Node<>(e); // Create a new node
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) // the new node is the only node in list
tail = head;
}
/** Add an element to the end of the list */
public void addLast(E e) {
Node<E> newNode = new Node<>(e); // Create a new for element e
if (tail == null) {
head = tail = newNode; // The new node is the only node in list
}
else {
tail.next = newNode; // Link the new with the last node
tail = newNode; // tail now points to the last node
}
size++; // Incr.
2.(Sorted list array implementation)This sorted list ADT discussed .pdfarshin9
2.(Sorted list: array implementation)This sorted list ADT discussed in class should be extended
by the addition of two new methods:
//Interface: ArrayListADT
//works for int
public interface ArrayListADT {
public boolean isEmpty(); //Method to determine whether the list is empty.
public boolean isFull(); //Method to determine whether the list is full.
public int listSize(); //Method to return the number of elements in the list.
public int maxListSize(); //Method to return the maximum size of the list.
public void print(); //Method to output the elements of the list.
public boolean isItemAtEqual(int location, int item); //Method to determine whether item is
the same as the item in the list at location.
public void insertAt(int location, int insertItem); //Method to insert insertItem in the list at
the position
public void insertEnd(int insertItem); //Method to insert insertItem at the end of the list.
public void removeAt(int location); //Method to remove the item from the list at location.
public int retrieveAt(int location); //Method to retrieve the element from the list at location.
public void replaceAt(int location, int repItem); //Method to replace the element in the list at
location with repItem.
public void clearList(); //Method to remove all the elements from the list.
public int search(int searchItem); //Method to determine whether searchItem is in the list.
public void remove(int removeItem); //Method to remove an item from the list.
}
//Class: ArrayListClass implements
//Interface: ArrayListADT
public abstract class ArrayListClass implements ArrayListADT {
protected int length; //to store the length of the list
protected int maxSize; //to store the maximum size of the list
protected int[] list; //array to hold the list elements
//Default constructor
public ArrayListClass() {
maxSize = 100;
length = 0;
list = new int[maxSize];
}
//Alternate Constructor
public ArrayListClass(int size) {
if(size <= 0) {
System.err.println(\"The array size must be positive. Creating an array of size 100.\");
maxSize = 100;
}
else
maxSize = size;
length = 0;
list = new int[maxSize];
}
public boolean isEmpty() {
return (length == 0);
}
public boolean isFull() {
return (length == maxSize);
}
public int listSize() {
return length;
}
public int maxListSize() {
return maxSize;
}
public void print() {
for (int i = 0; i < length; i++)
System.out.print(list[i] + \" \");
System.out.println();
}
public boolean isItemAtEqual(int location, int item) {
if (location < 0 || location >= length) {
System.err.println(\"The location of the item to be compared is out of range.\");
return false;
}
return list[location]== item;
}
public void clearList() {
for (int i = 0; i < length; i++)
list[i] = 0;
length = 0;
System.gc(); //invoke the Java garbage collector
}
public void removeAt(int location) {
if (location < 0 || location >= length)
System.err.println(\"The location of the item to be removed is out of range.\");
else {
for(int i = location; i < length - 1; i++)
list[i] .
File LinkedList.java Defines a doubly-l.pdfConint29
File: LinkedList.java
/**
* Defines a doubly-linked list class
*/
import java.util.NoSuchElementException;
public class LinkedList {
private class Node {
private T data;
private Node next;
private Node prev;
public Node(T data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
private int length;
private Node first;
private Node last;
private Node iterator;
/**** CONSTRUCTORS ****/
/**
* Instantiates a new LinkedList with default values
* @postcondition
*/
public LinkedList() {
}
/**
* Converts the given array into a LinkedList
* @param array the array of values to insert into this LinkedList
* @postcondition
*/
public LinkedList(T[] array) {
}
/**
* Instantiates a new LinkedList by copying another List
* @param original the LinkedList to copy
* @postcondition a new List object, which is an identical,
* but separate, copy of the LinkedList original
*/
public LinkedList(LinkedList original) {
}
/**** ACCESSORS ****/
/**
* Returns the value stored in the first node
* @precondition
* @return the value stored at node first
* @throws NoSuchElementException
*/
public T getFirst() throws NoSuchElementException {
return null;
}
/**
* Returns the value stored in the last node
* @precondition
* @return the value stored in the node last
* @throws NoSuchElementException
*/
public T getLast() throws NoSuchElementException {
return null;
}
/**
* Returns the data stored in the iterator node
* @precondition
* @return the data stored in the iterator node
* @throw NullPointerException
*/
public T getIterator() throws NullPointerException {
return null;
}
/**
* Returns the current length of the LinkedList
* @return the length of the LinkedList from 0 to n
*/
public int getLength() {
return -1;
}
/**
* Returns whether the LinkedList is currently empty
* @return whether the LinkedList is empty
*/
public boolean isEmpty() {
return false;
}
/**
* Returns whether the iterator is offEnd, i.e. null
* @return whether the iterator is null
*/
public boolean offEnd() {
return false;
}
/**** MUTATORS ****/
/**
* Creates a new first element
* @param data the data to insert at the front of the LinkedList
* @postcondition
*/
public void addFirst(T data) {
return;
}
/**
* Creates a new last element
* @param data the data to insert at the end of the LinkedList
* @postcondition
*/
public void addLast(T data) {
return;
}
/**
* Inserts a new element after the iterator
* @param data the data to insert
* @precondition
* @throws NullPointerException
*/
public void addIterator(T data) throws NullPointerException{
return;
}
/**
* removes the element at the front of the LinkedList
* @precondition
* @postcondition
* @throws NoSuchElementException
*/
public void removeFirst() throws NoSuchElementException {
return;
}
/**
* removes the element at the end of the LinkedList
* @precondition
* @postcondition
* @throws NoSuchElementException
*/
public void removeLast() throws NoSuchElementException {
return;
}
/**
* removes the element referenced by the iterator
* @precondition
* @pos.
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...davidwarner122
FOR MORE CLASSES VISIT
www.tutorialoutlet.com
Below is a given ArrayList class and Main class in search algorithms. Please modify the existing program so it can time the sequential search and the binary search methods several times each for randomly generated values, and record the results in a table. Do not time individual searches, but groups of them. For example, time 100 searches together or 1,000 searches together. Compare the running times of these two search methods that are obtained during the experiment.
For each task, submit your source java code file.(1) Objective Im.pdfdhavalbl38
For each task, submit your source java code file.
(1) Objective: Implement Link List
Write a class that maintains the scores for a game application. Implement the addition and
removal function to update the database. The gamescore.txt contains player’ name and score data
record fields separated by comma. For Removal function, uses the name field to select record to
remove the game score record.
Download – List.java, LList.java, Dlink.java, GameEntry.java, gamescore.txt
(a)Read gamescore.txt to initialize the Linked list in sorted order. (1 point)
(b)Provide Remove and Add function for user to update the sorted linked list. (1 point)
(2)Add a reverse function to the LList.java class to reverse the order of the linked list. (2 points).
---------------------------------------------------------------------------------------------------------------------
-----------------------------------------
//gamescore.txt
Mike,1105
Rob,750
Paul,720
Anna,660
Rose,590
Jack,510
--------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------
//DLink.java
/** Source code example for \"A Practical Introduction to Data
Structures and Algorithm Analysis, 3rd Edition (Java)\"
by Clifford A. Shaffer
Copyright 2008-2011 by Clifford A. Shaffer
*/
/** Doubly linked list node */
class DLink {
private E element; // Value for this node
private DLink next; // Pointer to next node in list
private DLink prev; // Pointer to previous node
/** Constructors */
DLink(E it, DLink p, DLink n)
{ element = it; prev = p; next = n; }
DLink(DLink p, DLink n) { prev = p; next = n; }
/** Get and set methods for the data members */
DLink next() { return next; }
DLink setNext(DLink nextval)
{ return next = nextval; }
DLink prev() { return prev; }
DLink setPrev(DLink prevval)
{ return prev = prevval; }
E element() { return element; }
E setElement(E it) { return element = it; }
}
--------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------
//GameEntry.java
public class GameEntry {
protected String name;
protected int score;
public GameEntry(String n, int s) {
name = n;
score = s;
}
public String getName() {return name;}
public int getScore() {return score;}
public String toString() {
return \"(\"+name+\",\"+score+\")\";
}
}
--------------------------------------------------------------------------------------------------------------------
----------------------------------
//List.java
/** Source code example for \"A Practical Introduction to Data
Structures and Algorithm Analysis, 3rd Edition (Java)\"
by Clifford A. Shaffer
Copyright 2008-2011 by Clifford A. Shaffer
*/
/** List ADT */
public interface List {
/** Remove all contents from the list, so it is once again
empty. Client is responsible for reclaiming storage
used by the list elements. */
p.
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdfarrowmobile
Here is the editable code:
Solution
import java.util.NoSuchElementException;
public class DoublyLinkedListImpl {
private Node head;
private Node tail;
private int size;
public DoublyLinkedListImpl() {
size = 0;
}
private class Node {
E element;
Node next;
Node prev;
public Node(E element, Node next, Node prev) {
this.element = element;
this.next = next;
this.prev = prev;
}
}
public int size() { return size; }
public boolean isEmpty() { return size == 0; }
public void addFirst(E element) {
Node tmp = new Node(element, head, null);
if(head != null ) {head.prev = tmp;}
head = tmp;
if(tail == null) { tail = tmp;}
size++;
System.out.println(\"adding: \"+element);
}
/**
* adds element at the end of the linked list
* @param element
*/
public void addLast(E element) {
Node tmp = new Node(element, null, tail);
if(tail != null) {tail.next = tmp;}
tail = tmp;
if(head == null) { head = tmp;}
size++;
System.out.println(\"adding: \"+element);
}
public void iterateForward(){
System.out.println(\"iterating forward..\");
Node tmp = head;
while(tmp != null){
System.out.println(tmp.element);
tmp = tmp.next;
}
}
/**
* this method walks backward through the linked list
*/
public void iterateBackward(){
System.out.println(\"iterating backword..\");
Node tmp = tail;
while(tmp != null){
System.out.println(tmp.element);
tmp = tmp.prev;
}
}
public E removeFirst() {
if (size == 0) throw new NoSuchElementException();
Node tmp = head;
head = head.next;
head.prev = null;
size--;
System.out.println(\"deleted: \"+tmp.element);
return tmp.element;
}
public E removeLast() {
if (size == 0) throw new NoSuchElementException();
Node tmp = tail;
tail = tail.prev;
tail.next = null;
size--;
System.out.println(\"deleted: \"+tmp.element);
return tmp.element;
}
public static void main(String a[]){
DoublyLinkedListImpl dll = new DoublyLinkedListImpl();
dll.addFirst(10);
dll.addFirst(34);
dll.addLast(56);
dll.addLast(364);
dll.iterateForward();
dll.removeFirst();
dll.removeLast();
dll.iterateBackward();
}
}
import java.util.Scanner;
/* Class Node */
class Node
{
protected int data;
protected Node next, prev;
/* Constructor */
public Node()
{
next = null;
prev = null;
data = 0;
}
/* Constructor */
public Node(int d, Node n, Node p)
{
data = d;
next = n;
prev = p;
}
/* Function to set link to next node */
public void setLinkNext(Node n)
{
next = n;
}
/* Function to set link to previous node */
public void setLinkPrev(Node p)
{
prev = p;
}
/* Funtion to get link to next node */
public Node getLinkNext()
{
return next;
}
/* Function to get link to previous node */
public Node getLinkPrev()
{
return prev;
}
/* Function to set data to node */
public void setData(int d)
{
data = d;
}
/* Function to get data from node */
public int getData()
{
return data;
}
}
/* Class linkedList */
class linkedList
{
protected Node start;
protected Node end ;
public int size;
/* Constructor */
public linkedList()
{
start = null;
end = null;
size = 0;
}
/* Function to check if list is empty */
public boolean isE.
So I have this code(StackInAllSocks) and I implemented the method but.pdfaksahnan
So I have this code( StackInAllSocks ) and I implemented the method but I can't seem to figure
out why there isn't anything showing up on the console. It should pop,peek and push b using the
methods from the class called ArrayListTen . The ArrayListTen works fine and compiles the
tested code of Rigth# but for StackInAllSocks it doesn't complete at all. note that file
VodeDodeis not to be changed is just a Node storage area of the array list.
Did I implement the method on StackInAllSocks correctly? if so, should I not use the method
from the ArrayListTen .?
__________________________________________________________________________
: the code is : VodeDodeis
class VodeDode<T> {
private T data;
private VodeDode<T> next;
private VodeDode<T> prev;
public VodeDode(T data) {
this.data = data;
this.next = null;
this.prev = null;}
public T getData() {
return data;}
public void setData(T data) {
this.data = data;}
public VodeDode<T> getNext() {
return this.next;}
public void setNext(VodeDode<T> next) {
this.next = next;}
public VodeDode<T> getPrev() {
return this.prev;}
public void setPrev(VodeDode<T> prev) {
this.prev = prev;}
@Override
public String toString() {
return data.toString();}}
_________________________________________________________________________
CODE that works fine called ArrayListTen:
import java.util.Iterator;
public class ArrayListTen<T> implements Iterable<T> {
private VodeDode<T> head; //beginning of list
private VodeDode<T> tail; //end of list
private int size;
private VodeDode<T> new_item;
public ArrayListTen( ){
this.head = null;
this.tail = null;
this.size = 0;}
public int lenght() {
return size ;}
public T getBegin() {
if (this.head != null) {
return head.getData();}
else { return null;}}
public void addBegin(T value) {
VodeDode<T> newVodeDode =new VodeDode<T>(value);
if (this.head== null) {
head = newVodeDode;
tail =newVodeDode;}
else {VodeDode<T> temp = head;
head = newVodeDode;
head.setNext(temp);}
size++;}
public T removeBegin() {
if(this.head == null) {
return null;}
else {T current = head.getData();
if (tail == head) {
tail = null;
head = null;
} else {
head = head.getNext();
head.setPrev(null);}size--;
return current;}}
public T getEnd() {
if (tail != null) {
return tail.getData();
} else {
return null;}}
public void addEnd(T value) {
VodeDode<T> newVodeDode = new VodeDode<T>(value);
if (this.tail == null) {
head = newVodeDode;
tail = newVodeDode;
} else {
newVodeDode.setPrev(tail);
tail.setNext(newVodeDode);
tail = newVodeDode;}
size++;}
public T removeEnd() {
if(this.tail == null) {
return null;}
else {
T current = tail.getData();//was head.
if (head == tail) {
head = null;
tail = null;
} else {
tail = tail.getPrev();
tail.setNext(null);}
size--;
return current;}}
public T removeBN(T value) {
VodeDode<T> currVodeDode = head;
VodeDode<T> prevVodeDode = null;
while(currVodeDode != null){
if(currVodeDode.getData().equals(value)){
if(prevVodeDode != null){
prevVodeDode.setNext(currVodeDode.getNext());}
else{
head = curr.
Java Foundations StackADT-java --- - Defines the interface to a stack.docxVictorXUQGloverl
Java Foundations
StackADT.java
/**
* Defines the interface to a stack collection.
*
* @author Java Foundations
* @version 4.0
*/
public interface StackADT<T> {
/**
* Adds the specified element to the top of this stack.
*
* @param element element to be pushed onto the stack
*/
public void push(T element);
/**
* Removes and returns the top element from this stack.
*
* @return the element removed from the stack
* @throws EmptyCollectionException if the stack is empty
*/
public T pop();
/**
* Returns the top element of this stack without removing it from the stack.
*
* @return the element on top of the stack. It is not removed from the stack
* @throws EmptyCollectionException if the stack is empty
*/
public T peek();
/**
* Returns true if this stack contains no elements.
*
* @return true if the stack is empty, false if the stack is not empty
*/
public boolean isEmpty();
/**
* Returns the number of elements in this stack.
*
* @return the number of elements in the stack
*/
public int size();
}
QueueADT.java
/**
* QueueADT defines the interface to a queue collection.
*
* @author Java Foundation
* @version 4.0
*/
public interface QueueADT<T> {
/**
* Adds one element to the rear of this queue.
*
* @param element the element to be added to the rear of the queue
*/
public void enqueue(T element);
/**
* Removes and returns the element at the front of this queue.
*
* @return the element at the front of the queue
* @throws EmptyCollectionException if the queue is empty
*/
public T dequeue();
/**
* Returns without removing the element at the front of this queue.
*
* @return the first element in the queue
* @throws EmptyCollectionException if the queue is empty
*/
public T first();
/**
* Returns true if this queue contains no elements.
*
* @return true if the queue is empty, false if the queue is not empty
*/
public boolean isEmpty();
/**
* Returns the number of elements in this queue.
*
* @return the number of elements in the queue
*/
public int size();
}
LinkedDeque.java
public class LinkedDeque<T> implements QueueADT<T>, StackADT<T>, DequeADT<T> {
// inner class for a double linked list node
private class DNode<T> {
private T element;
private DNode<T> prev, next;
}
// data fields for the LinkedDeque class
private DNode<T> front, rear;
private int size;
// deque interface methods
@Override
public void addFirst(T element) {
// create a new node and set it up
DNode<T> newNode = new DNode<T>();
newNode.element = element; // from param to new node obj
newNode.prev = newNode.next = null;
if(this.isEmpty()) {
// we are making the only node in the deque
this.rear = this.front = newNode;
} else {
// there already exists a new node
// so, put the new node before the front node
newNode.next = this.front;
this.front.prev = newNode;
this.front = newNode;
}
this.size++;
}
@Override
public T removeFirst() {
T grabbedElt = this.getFirst(); // checks for empty for us
if.
1.The Excavata includes taxa that are photosynthetic, parasitic, sym.pdfravikapoorindia
1.The Excavata includes taxa that are photosynthetic, parasitic, symbiotic and heterotrophic.
Many of the taxa lack mitochondria, and, therefore, seemed to conform to the requirements of an
archaic premitochondrial ancestor of all eukaryotes. This theory, called the Archezoa
Hypothesis, was created by Cavalier-Smith (1983). The former archezoa began to find homes in
interesting and unexpected places. Patterson (1999) and Simpson and Patterson (2001) defined a
striking structural similarity that many of the former archezoan taxa possessed, a feeding groove
called an excavate. The excavate was a groove that ran longitudinally on the cell surface and was
associated with at least one recurrent flagellum, which set up currents in the groove that served
to concentrate suspended particles and move them to a cytostome. Simpson (2003) identified
seven such groups that had such an excavate apparatus: the Core Jakobids, Malawimonas,
Trimastix, Carpediemonas, Retortomonads, Diplomonads, and the Heterolobosids
(amoeboflagellates). Many of the excavate taxa were mitochondriate and had clear affinities
with taxa that did not bear an excavate. So, by 2003 (Simpson 2003 and Cavalier-Smith 2003b)
at least 10 groups (we interpret it as 11 groups) had been identified as excavate taxa (see Table
1). Burki et al. (2008) and Hampl et al. (2009) confirmed the monophyly of the excavates by
phylogenomic analyses relative to members of the other supergroups. Furthermore, the excavates
appear to be a very deep-rooting group, equivalent to the unikonts (Opisthokonta), and the
bikonts (Chromalveolata + Rhizaria + Archaeplastida).
2.It is very difficult to discover drug against TB sice the bacteria which is mycobacterium is
thermostabile and made up of mycolic acid . An increasing evidence of multidrug resistance in
TB is the major problem in developing drug against TB. The mycobacterium is able to
accumulate drug and become resistant to these drug. This bacteria develop allernative
mechanism to become resistant to the drug.
Malaria
some antimalarials can only be used in certain areas of the world because parasites are resistant
to some drugs. For example, chloroquine can only be used to prevent Plasmodium falciparum in
regions of South America because Plasmodium falciparum is completely resistant to chloroquine
in Africa and Asia.
E. ameoba histoilica
Solution
1.The Excavata includes taxa that are photosynthetic, parasitic, symbiotic and heterotrophic.
Many of the taxa lack mitochondria, and, therefore, seemed to conform to the requirements of an
archaic premitochondrial ancestor of all eukaryotes. This theory, called the Archezoa
Hypothesis, was created by Cavalier-Smith (1983). The former archezoa began to find homes in
interesting and unexpected places. Patterson (1999) and Simpson and Patterson (2001) defined a
striking structural similarity that many of the former archezoan taxa possessed, a feeding groove
called an excavate. The excavate was a groove that ran longit.
1. According to morphological species concept focus on external phys.pdfravikapoorindia
1. According to morphological species concept focus on external physical characters such as
size, shape, color structure of the organism .
2. Biological species concept explains why the members of species are resemble to one another.
When two organisms are breeded their genes pass into their combined offspring.
3. Phylogenetic species concept defines a species as a group having a shared and unique
evolotionary history. The offsprings in the concept are parental pattern of ancestry and descent.
4. Unified species concept achieved by treating existing as separately and secondary species
criteria as different line of evidence.
5. From the above quenstion species XL and XXL are showing variation in their morphology and
their number of chromosome. The remaining species show variation in the colour of shell.
6. From the above infromation the correct answer is option \"e\" all the above.
Solution
1. According to morphological species concept focus on external physical characters such as
size, shape, color structure of the organism .
2. Biological species concept explains why the members of species are resemble to one another.
When two organisms are breeded their genes pass into their combined offspring.
3. Phylogenetic species concept defines a species as a group having a shared and unique
evolotionary history. The offsprings in the concept are parental pattern of ancestry and descent.
4. Unified species concept achieved by treating existing as separately and secondary species
criteria as different line of evidence.
5. From the above quenstion species XL and XXL are showing variation in their morphology and
their number of chromosome. The remaining species show variation in the colour of shell.
6. From the above infromation the correct answer is option \"e\" all the above..
1)calcium(pH-dependent regulation of lysosomal calcium in macrophage.pdfravikapoorindia
1)calcium(pH-dependent regulation of lysosomal calcium in macrophages)
Pulmonary macrophages are motile cells that respond to contact with suitable surfaces or
micron-sized objects by undergoing movements that lead to spreading and phagocytosis. There is
evidence that interactions of actin and other proteins in the cortical cytoplasm of macrophages
provide the motor power for these movements and that variations in free calcium concentrations
in the cortical cytoplasm of macrophages might control their directionality (1). If the plasma
membrane maintains a large electrochemical gradient of calcium between the extracellular
environment and the cytoplasm, a slight alteration of its activity could result in a considerable
variation of cytoplasmic free calcium concentrations. If contact of the external surface of the
plasma membrane with certain surfaces were somehow coupled to the calcium gradient-
maintaining activity of the membrane, the interaction could lead to changes in peripheral
cytoplasmic calcium levels. We have studied calcium transport across the macrophage plasma
membrane, using phagocytic vesicles. Phagocvtic vesicles arise from the internalization of
plasma membrane and thus constitute a system to study easily its inner surface. Furthermore,
when prepared from macrophages that have ingested oil droplets, they can be purified rapidly by
flotation with good yield and in an intact state (2). Using this approach, we have characterized a
high affinity MgATP-dependent calcium pump located in the inner side of the plasma membrane
2).the protein was translated using ribosomes inside the ER(
The endomembrane system (endo- = “within”) is a group of membranes and organelles in
eukaryotic cells that works together to modify, package, and transport lipids and proteins. It
includes a variety of organelles, such as the nuclear envelope and lysosomes, which you may
already know, and the endoplasmic reticulum and Golgi apparatus, which we will cover shortly.
Although it\'s not technically inside the cell, the plasma membrane is also part of the
endomembrane system. As we\'ll see, the plasma membrane interacts with the other
endomembrane organelles, and it\'s the site where secreted proteins (like the pancreatic enzymes
in the intro) are exported. Important note: the endomembrane system does not include
mitochondria, chloroplasts, or peroxisomes.
Let\'s take a closer look at the different parts of the endomembrane system and how they
function in the shipping of proteins and lipids.
The endoplasmic reticulum
The endoplasmic reticulum (ER) plays a key role in the modification of proteins and the
synthesis of lipids. It consists of a network of membranous tubules and flattened sacs. The discs
and tubules of the ER are hollow, and the space inside is called the lumen.
Rough ER
The rough endoplasmic reticulum (rough ER) gets its name from the bumpy ribosomes attached
to its cytoplasmic surface. As these ribosomes make proteins, they feed the newly formin.
Viral genomes may be circular, as in the polyomaviruses, or linear, .pdfravikapoorindia
Viral genomes may be circular, as in the polyomaviruses, or linear, as in the adenoviruses. A
virus has either a DNA or an RNA genome and is called a DNA virus or an RNA . Plant viruses
mostly have single-stranded RNA genomes (exception retrovirus) and bacteriophages mostly
tend to have double-stranded DNA genomes
Solution
Viral genomes may be circular, as in the polyomaviruses, or linear, as in the adenoviruses. A
virus has either a DNA or an RNA genome and is called a DNA virus or an RNA . Plant viruses
mostly have single-stranded RNA genomes (exception retrovirus) and bacteriophages mostly
tend to have double-stranded DNA genomes.
This is an example of a Lewis Acid. The CO2 acts like an acid becaus.pdfravikapoorindia
This is an example of a Lewis Acid. The CO2 acts like an acid because it is an electron pair
acceptor (a lewis base is an electron pair donor).
Solution
This is an example of a Lewis Acid. The CO2 acts like an acid because it is an electron pair
acceptor (a lewis base is an electron pair donor)..
The Vestibular System, which is a contributed to our balance system .pdfravikapoorindia
The Vestibular System, which is a contributed to our balance system and our sense of spatial
orientation, is the sensory system that provides the dominant input about movement and
equilibrioception. Vestibular sense provides information related to movement and head
position.The vestibular system includes the part of the inner ear and brain that help control
balance and eye movements. If the system is damaged dy disease, aging,or injury, vestibular
disorders can result, and are often associated with one or more of these systoms, among others:
Vertigo and dizziness
Imbalance and spatial disorientation
Vision disturbance
Hearing changes
Cognitive and / or psychological change
Other symptoms
The type and severity of vestibular disorder can vary considerably, and be frightening and
difficult to describe. People affacted by vestibular disorders may be perceived as inattentive,
overly, anxious, or seeking attention.
The following is a list of systems that have been reported by people with vestibular disorders.
VERTIGO AND DIZZINESS
Spinning or whirling sensation; a feeling the person or world moving when it is not (vertigo)
Symptoms can be present while sitting still, in specific positions, or with movement
Lightheaded, floating, or rocking sensation (dizziness)
BALANCE AND SPATIAL ORIENTATION
Imbalance, stumbling, difficulty walking straight or when turning
Clumsiness or difficulty with coordination
Difficulty maintaining straight posture; head may be tilted to the side
Sessitivity to change in walking surface or footwear
Muscle and joint pain
VISION
Trouble focusing or tracking objects with the eyes; objects or words on a page seem to bounce,
jump,float, or blur or may appear doubled
Discomfort from busy visual environments such as traffic,crowds, stores, and patterns
Sensitivity to light,glare,moving or flickering light;fluorescent lights may be especially
troublesome
Sensitivity to certain type of computer monitors and digital televisions
Tendencyto focus on nearby objects; increased discomfort when focusing at a distance
Increased night blindness; difficlty walking in the dark
Poor depth perception
HEARING CHANGES
Hearing loss; distorted or fluctuating hearing
Tinnitus
Sensitivity to loud noises or environments
Sudden loud sound may increase symptoms of vertigo, dizziness, or imbalance
COGNITIVE
Difficulty concentration and paying attention; easily distracted
Forgetfulness and short- term memory lapses
Confusion, disorientation,difficulty comperhending direction or instructions
PSYCHOLOGICAL
Loss of self-reliance, self-confidence, self-esteem
Anxiety, panic, social isolation
Depression
The VESTIBULAR SYSTEM is a collection of structures in your inner ear that provides you
with your sense of balance and an awareness of your spatial orientation, meaning a sense of
whether you ear right-side up or up- side down. Your brain then integates that information with
other sensory information from your body to coordinate smooth and well- timed body
moveme.
The inherent risk for an assertion about a derivative is its suscept.pdfravikapoorindia
The inherent risk for an assertion about a derivative is its susceptibility to a material
misstatement, assuming there are no related controls. Examples of considerations that might
affect the investor\'s assessment of inherent risk for assertions about a derivative or security
include the following.
Auditing Standard No. 12, Identifying and Assessing Risks of Material Misstatement, requires
the auditor or investor to obtain an understanding of internal control that will enable the auditor
to—
Solution
The inherent risk for an assertion about a derivative is its susceptibility to a material
misstatement, assuming there are no related controls. Examples of considerations that might
affect the investor\'s assessment of inherent risk for assertions about a derivative or security
include the following.
Auditing Standard No. 12, Identifying and Assessing Risks of Material Misstatement, requires
the auditor or investor to obtain an understanding of internal control that will enable the auditor
to—.
1 D2 the decrease in entropy of the system is offset by an incr.pdfravikapoorindia
1: D
2: the decrease in entropy of the system is offset by an increase in the entropy of the
surroundings caused by the release of heat from the system to the surroundings
Solution
1: D
2: the decrease in entropy of the system is offset by an increase in the entropy of the
surroundings caused by the release of heat from the system to the surroundings.
Miller is US based investor and co-founder and current chairman of U.pdfravikapoorindia
Miller is US based investor and co-founder and current chairman of US investment group Legg
Mason Capital Management. Miller always pick stock based of multiple valuation such as high
P/E and low P/E, high price-to-book and low-price-to-book. So, he does not Pick stocks based on
their fundamentals, such as high intrinsic-value stocks.
So, option (D) is not part of Miller’s investment style
Solution
Miller is US based investor and co-founder and current chairman of US investment group Legg
Mason Capital Management. Miller always pick stock based of multiple valuation such as high
P/E and low P/E, high price-to-book and low-price-to-book. So, he does not Pick stocks based on
their fundamentals, such as high intrinsic-value stocks.
So, option (D) is not part of Miller’s investment style.
Marijuana plant belongs to the genus Cannabis. It is native to the C.pdfravikapoorindia
Marijuana plant belongs to the genus Cannabis. It is native to the Caucasus region of eastern
Europe, India, and Iran. In these regions, the plants were cultivated from ancient times. The plant
grows in open and disturbed habitats in wild. The plant grows best in mild climatic conditions.
Cannabis plants are dioecious. There are 3 species identified, all of which can hybridize with
each other. The plant is an annual herb. It is small that grows to 2 to 5 meters, usually erect, with
variable stems.
Stem: Resinous pubescence, angular, hollow
Leaves: basal, alternate, stipulate, long petiolate, and palmate. They are rarely single, lanceolate,
serrate. Leaves are 10 cm long to 1.5 cm broad.
Flowers: Monoecious or dioecious. Male flowers located in the axillae, with terminal panicles,
apetalous, contain 5 petals and 5 poricidal stamens
Female flowers: germinate in the axils and terminally, contain 1-ovulate ovary
Fruit: brown fruit with shining achene, plain, tightly embracing the seed, fleshy endosperm and
curved embryo.
Habitat: Native to central and south Asia, Europe, and China. Plants adapt to soil and climatic
conditions easily. Mild climatic conditions and moderate to minimum annual rainfall required.
Can grow in fertile, neutral, slightly alkaline, well-drained silt or clay loams. The plants do not
grow on acid, sandy soils.
Propagation: Through seeds. Seeds are stored in cool and dry palce where they remain viable for
about 3 years. Seeds germinate well if sown before early spring, that is, around March. Seeds
germinate at low temperatures when moisture is abundant.
Plants are ready for harvest in 4 – 6 months after planting, and depends on the variety cultivated.
Male plants turn yellow and die whereas female plants survive until the seed ripens. Therefore,
male plants can be harvested earlier than female plants. Seeds are harvested from female plants
when the seeds fall off when the stem is shaken.
Solution
Marijuana plant belongs to the genus Cannabis. It is native to the Caucasus region of eastern
Europe, India, and Iran. In these regions, the plants were cultivated from ancient times. The plant
grows in open and disturbed habitats in wild. The plant grows best in mild climatic conditions.
Cannabis plants are dioecious. There are 3 species identified, all of which can hybridize with
each other. The plant is an annual herb. It is small that grows to 2 to 5 meters, usually erect, with
variable stems.
Stem: Resinous pubescence, angular, hollow
Leaves: basal, alternate, stipulate, long petiolate, and palmate. They are rarely single, lanceolate,
serrate. Leaves are 10 cm long to 1.5 cm broad.
Flowers: Monoecious or dioecious. Male flowers located in the axillae, with terminal panicles,
apetalous, contain 5 petals and 5 poricidal stamens
Female flowers: germinate in the axils and terminally, contain 1-ovulate ovary
Fruit: brown fruit with shining achene, plain, tightly embracing the seed, fleshy endosperm and
curved embryo.
Habitat: Native .
InheritenceJava supports inheritance and thus, variables and metho.pdfravikapoorindia
Inheritence
Java supports inheritance and thus, variables and methods of the superclass are inherited and can
be used by the subclass. but the private members of the superclass that cannot be accessed
directly from the subclass.
inheritenceexample.java
class Animal {//super class
public Animal() {
System.out.println(\"A new animal has been created!\");
}
public void eat() {//super class methods eat and moves
System.out.println(\"An animal eats...\");
}
public void moves() {
System.out.println(\"An animal movess...\");
}
}
class Cow extends Animal {//Cow subclass
public Cow() {
super();//used to invoke super class constructer
System.out.println(\"A new cow has been created!\");
}
@Override
public void eat() {
System.out.println(\"A Cow eats...\");
}
@Override
public void moves() {
System.out.println(\"A Cow movess...\");
}
}
class Dog extends Animal {//sub class Dog
public Dog() {
super();
System.out.println(\"A new dog has been created!\");
}
@Override
public void eat() {
System.out.println(\"A dog eats...\");
}
@Override
public void moves() {
System.out.println(\"A dog movess...\");
}
}
public class inhertenceexample {//main class
public static void main(String[] args) {
Animal animal = new Animal();
Cow Cow = new Cow();
Dog dog = new Dog();
System.out.println();
animal.eat();
animal.moves();
Cow.eat();
Cow.moves();
dog.eat();
dog.moves();
}
}
output
A new animal has been created!
A new animal has been created!
A new cow has been created!
A new animal has been created!
A new dog has been created!
An animal eats...
An animal movess...
A Cow eats...
A Cow movess...
A dog eats...
A dog movess...
method overloading and method overiding
same multiple method\'s with different arguments is known as method overloading
There are two ways to overload the method in java
By changing number of arguments
By changing the data type
method overloading example
calculationresult.java
class Calculationresult{
void mul(int a,int b){System.out.println(a*b);}
void mul(int a,int b,int c){System.out.println(a*b*c);}
public static void main(String args[]){
Calculationresult obj=new Calculationresult();
obj.mul(10,10,10);
obj.mul(20,20);
}
}
output
1000
400
method overiding
If subclass has the same method as declared in the parent class, it is known as method overriding
in java.
car.java
class Vehicle{
void run(){System.out.println(\"Vehicle is running\");}
}
class car extends Vehicle{
void run(){System.out.println(\"car is running safely\");}
public static void main(String args[]){
car obj = new car();
obj.run();
}}
output
car is running safely
Solution
Inheritence
Java supports inheritance and thus, variables and methods of the superclass are inherited and can
be used by the subclass. but the private members of the superclass that cannot be accessed
directly from the subclass.
inheritenceexample.java
class Animal {//super class
public Animal() {
System.out.println(\"A new animal has been created!\");
}
public void eat() {//super class methods eat and moves
System.ou.
It is the temporal lobe of cerebrum. It is situated beneath the late.pdfravikapoorindia
It is the temporal lobe of cerebrum. It is situated beneath the lateral fissure of brain. This part of
brain is directly influence on language comprehension, visual memory, and emotion association.
Solution
It is the temporal lobe of cerebrum. It is situated beneath the lateral fissure of brain. This part of
brain is directly influence on language comprehension, visual memory, and emotion association..
In cat,The ductus deferens also called the vas deferens leaves the t.pdfravikapoorindia
In cat,The ductus deferens also called the vas deferens leaves the tail of the epididymis along
with the testicular vessels and nerves, enters the spermatic cord.
The spermatic cord enters the abdominal cavity, it contains the ductus deferens, blood vessels
and nerves.
The site of passage through the body wall is known as the inguinal canal.
The ductus deferens of the opposite sides then converge and soon enter the urethra, which leads
to the penis.
Various accessory glands, which secrete the seminal fluid, are associated with the ends of the
ductus deferens and adjacent part of the urethra.
In the cat, a small prostate gland surrounds the point of entrance of the two ductus deferens and
the adjacent urethra.
At the caudal end of the pelvic canal, a pair of Cowper´s glands enter the urethral canal, but the
male cat does not have a seminal vesicle as does the human male.
In human , From the epididymis, the ductus deferens ascends posterior to the testes and enters
the spermatic cord that connects the testes to the rest of the body.
It continues with the spermatic cord,and entering the pelvic body cavity at the inguinal canal.
Between the ureters and the prostate, the ductus deferens expands its diameter considerably in a
region known as the ampulla before narrowing and joining with the seminal vesicles at the
ejaculatory duct inside the prostate.
The seminal vesicles are a pair of glands that are positioned below the urinary bladder and lateral
to the vas deferens. Each vesicle consists of a single tube folded and coiled on itself, with
occasional diverticula in its wall.
The excretory duct of each seminal gland unites with the corresponding vas deferens to form the
two ejaculatory ducts, which immediately pass through the substance of the prostate gland.
The seminal vesicles secrete a significant proportion of the fluid that ultimately becomes semen.
The vesicle produces a substance that causes the semen to become sticky and jelly-like after
ejaculation.
The thick secretions from the seminal vesicle contain proteins, enzymes, fructose, mucus,
vitamin, phosphorylcholine and prostaglandins.
Solution
In cat,The ductus deferens also called the vas deferens leaves the tail of the epididymis along
with the testicular vessels and nerves, enters the spermatic cord.
The spermatic cord enters the abdominal cavity, it contains the ductus deferens, blood vessels
and nerves.
The site of passage through the body wall is known as the inguinal canal.
The ductus deferens of the opposite sides then converge and soon enter the urethra, which leads
to the penis.
Various accessory glands, which secrete the seminal fluid, are associated with the ends of the
ductus deferens and adjacent part of the urethra.
In the cat, a small prostate gland surrounds the point of entrance of the two ductus deferens and
the adjacent urethra.
At the caudal end of the pelvic canal, a pair of Cowper´s glands enter the urethral canal, but the
male cat does not have a seminal vesicle as.
//*********************************************************
// VowelCount.java
//
// This program counts the number of vowels in a string
//*********************************************************
import java.util.Scanner;
public class VowelCount {
public static void main(String[] args) {
/*
* declare variables to store the number of each type of vowel
*/
int countA = 0, countE = 0, countI = 0, countO = 0, countU = 0;
Scanner scan = new Scanner(System.in);
// Get the string from the user (prompt and input)
System.out.println(\"Enter a string of characters:\");
String str = scan.nextLine();
// format for this part:
for (int i = 0; i < str.length(); i++) {
switch (str.charAt(i)) {
case \'a\':
case \'A\':
countA++;
break;
case \'e\':
case \'E\':
countE++;
break;
case \'i\':
case \'I\':
countI++;
break;
case \'o\':
case \'O\':
countO++;
break;
case \'u\':
case \'U\':
countU++;
break;
default:
break;
}
}
/*
* Remember: 1) condition should use method for getting string length 2)
* exp (in switch) should use method for returning a character
*/
// Output results
System.out.println(\"Number of each vowel in the string:\ a: \" + countA
+ \"\ e: \" + countE + \"\ i: \" + countI + \"\ o: \" + countO
+ \"\ u: \" + countU);
}
}
OUTPUT:
Enter a string of characters:
Hello! I am Finn from the land of Ooo.
Number of each vowel in the string:
a: 2
e: 2
i: 2
o: 6
u: 0
Solution
//*********************************************************
// VowelCount.java
//
// This program counts the number of vowels in a string
//*********************************************************
import java.util.Scanner;
public class VowelCount {
public static void main(String[] args) {
/*
* declare variables to store the number of each type of vowel
*/
int countA = 0, countE = 0, countI = 0, countO = 0, countU = 0;
Scanner scan = new Scanner(System.in);
// Get the string from the user (prompt and input)
System.out.println(\"Enter a string of characters:\");
String str = scan.nextLine();
// format for this part:
for (int i = 0; i < str.length(); i++) {
switch (str.charAt(i)) {
case \'a\':
case \'A\':
countA++;
break;
case \'e\':
case \'E\':
countE++;
break;
case \'i\':
case \'I\':
countI++;
break;
case \'o\':
case \'O\':
countO++;
break;
case \'u\':
case \'U\':
countU++;
break;
default:
break;
}
}
/*
* Remember: 1) condition should use method for getting string length 2)
* exp (in switch) should use method for returning a character
*/
// Output results
System.out.println(\"Number of each vowel in the string:\ a: \" + countA
+ \"\ e: \" + countE + \"\ i: \" + countI + \"\ o: \" + countO
+ \"\ u: \" + countU);
}
}
OUTPUT:
Enter a string of characters:
Hello! I am Finn from the land of Ooo.
Number of each vowel in the string:
a: 2
e: 2
i: 2
o: 6
u: 0.
Lithium has 3 electrons. Since an s orbital only .pdfravikapoorindia
Lithium has 3 electrons. Since an s orbital only holds two, we need both 1 s and 2 s
orbitals: Li: 1s2, 2s1
Solution
Lithium has 3 electrons. Since an s orbital only holds two, we need both 1 s and 2 s
orbitals: Li: 1s2, 2s1.
IO3- only exhibitsresonance ,since the lone pairs.pdfravikapoorindia
IO3- only exhibitsresonance ,since the lone pairs present on the Oxygen atoms
willlocalised.
Solution
IO3- only exhibitsresonance ,since the lone pairs present on the Oxygen atoms
willlocalised..
Model Attribute Check Company Auto PropertyCeline George
In Odoo, the multi-company feature allows you to manage multiple companies within a single Odoo database instance. Each company can have its own configurations while still sharing common resources such as products, customers, and suppliers.
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
The Indian economy is classified into different sectors to simplify the analysis and understanding of economic activities. For Class 10, it's essential to grasp the sectors of the Indian economy, understand their characteristics, and recognize their importance. This guide will provide detailed notes on the Sectors of the Indian Economy Class 10, using specific long-tail keywords to enhance comprehension.
For more information, visit-www.vavaclasses.com
How to Split Bills in the Odoo 17 POS ModuleCeline George
Bills have a main role in point of sale procedure. It will help to track sales, handling payments and giving receipts to customers. Bill splitting also has an important role in POS. For example, If some friends come together for dinner and if they want to divide the bill then it is possible by POS bill splitting. This slide will show how to split bills in odoo 17 POS.
The French Revolution, which began in 1789, was a period of radical social and political upheaval in France. It marked the decline of absolute monarchies, the rise of secular and democratic republics, and the eventual rise of Napoleon Bonaparte. This revolutionary period is crucial in understanding the transition from feudalism to modernity in Europe.
For more information, visit-www.vavaclasses.com
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;
}
}