/**
The LinkedList1 class implements a Linked list.
*/
class LinkedList1
{
/**
The Node class stores a list element
and a reference to the next node.
*/
private class Node
{
String value;
Node next;
/**
Constructor.
@param val The element to store in the node.
@param n The reference to the successor node.
*/
Node(String val, Node n)
{
value = val;
next = n;
}
/**
Constructor.
@param val The element to store in the node.
*/
Node(String val)
{
// Call the other (sister) constructor.
this(val, null);
}
}
private Node first; // list head
private Node last; // last element in list
/**
Constructor.
*/
public LinkedList1()
{
first = null;
last = null;
}
/**
The isEmpty method checks to see
if the list is empty.
@return true if list is empty,
false otherwise.
*/
public boolean isEmpty()
{
return first == null;
}
/**
The size method returns the length of the list.
@return The number of elements in the list.
*/
public int size()
{
int count = 0;
Node p = first;
while (p != null)
{
// There is an element at p
count ++;
p = p.next;
}
return count;
}
/**
The add method adds an element to
the end of the list.
@param e The value to add to the
end of the list.
*/
public void add(String e)
{
if (isEmpty())
{
first = new Node(e);
last = first;
}
else
{
// Add to end of existing list
last.next = new Node(e);
last = last.next;
}
}
/**
The add method adds an element at a position.
@param e The element to add to the list.
@param index The position at which to add
the element.
@exception IndexOutOfBoundsException When
index is out of bounds.
*/
public void add(int index, String e)
{
if (index < 0 || index > size())
{
String message = String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
// Index is at least 0
if (index == 0)
{
// New element goes at beginning
first = new Node(e, first);
if (last == null)
last = first;
return;
}
// Set a reference pred to point to the node that
// will be the predecessor of the new node
Node pred = first;
for (int k = 1; k <= index - 1; k++)
{
pred = pred.next;
}
// Splice in a node containing the new element
pred.next = new Node(e, pred.next);
// Is there a new last element ?
if (pred.next.next == null)
last = pred.next;
}
/**
The toString method computes the string
representation of the list.
@return The string form of the list.
*/
public String toString()
{
StringBuilder strBuilder = new StringBuilder();
// Use p to walk down the linked list
Node p = first;
while (p != null)
{
strBuilder.append(p.value + \"\ \");
p = p.next;
}
return strBuilder.toString();
}
/**
The remove method removes the element at an index.
@param index The index of the element to remove.
@return The element removed.
@exception IndexOutOfBoundsException When index is
out of bounds.
*/
public String remove(int index)
{
if (index < 0 || index >= size())
{
String message = String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
String element; // The element to return
if (index == 0)
{
// Removal of first item in the list
element.
import java.util.Iterator; import java.util.NoSuchElementException; /** * An implementation
of MyList with a linked list (a longer exercise would be to * implement the List interface as is
done in the class java.util.LinkedList: * the source of the LinkedList class is available from Sun.
Check it out). */ public class MyLinkedList implements MyList { // A private class to
represent a Node in the linked list private class Node { public E item;
public Node next; // a convenient constructor public Node(E o) {
this.item = o; this.next = null; } } // The start of the linked
list private Node head; // The last Node in the linked list private Node tail;
// Number of elements in the list private int size; /** * Creates an empty list (this
constructor is not necessary) */ public MyLinkedList() { } /** *
Returns the number of elements in this list. */ public int size() { return size;
} /** * Returns true if this list contains no elements. */ public boolean
isEmpty() { return size == 0; } /** * Appends the specified element to
the end of this list */ public boolean add(E o) { Node n = new Node(o);
// If this is the first element in the list if (head == null) { head = n;
} else { // If the list is not empty, use tail tail.next = n;
} // update tail tail = n; // update size size++;
return true; } /** * Empties this List */ public void clear() {
// update head, tail and size head = tail = null; size = 0; } /**
* Returns the element at the specified position in this list. */ public E get(int index) {
if (index < 0 || index >= size) { throw new
IndexOutOfBoundsException(\"index = \" + index); } // Find it
Node n = head; for (int i = 0; i < index; i++) { n = n.next; }
return n.item; } /** * Returns the index of the specified element (-1 if
there is no match) */ public int indexOf(Object o) { // If o is null
int index = 0; Node p = head; if (o == null) // look for a null element in the
list { while (p != null) { if (p.item == null) {
return index; } index++;
p = p.next; } } else // o is an object (use equals) {
while (p != null) { if (o.equals(p.item)) { return
index; } index++; p = p.next;
} } // if we get here, o is not in the list return -1; }
/** * Returns true if this list contains the specified element. */ public boolean
contains(Object o) { // easy with indexOf return indexOf(o) != -1; }
/** * Removes the element in the List at position index */ public boolean
remove(int index) { if (index < 0 || index >= size) { throw new
IndexOutOfBoundsException(\"index = \" + index); } // Find the
corresponding node Node prev = null, p = head; for (int i = 0; i < index; i++)
{ prev = p; p = p.next; } // Remove it
// Special case for the first node if (p == head) { head = head.next;
} else { prev.next = p.next; } // If the last node has been
removed, update tail if (p == tail) { tail = prev; } //
update size size--; return true; } /** * Removes the element
in the List at position index */ public boolean remove(Object o) { // easy
with indexOf and remove int index = i.
Note- Can someone help me with the private E get(int index- int curren (1).docxVictorzH8Bondx
Note: Can someone help me with the private E get(int index, int currentIndex, Node n)method. The code is not running. Also I need help with the public void add(int index, E element) method too. Please use the parameters provided with the code to solve. package edu.ust.cisc; import java.util.Iterator; import java.util.NoSuchElementException; public class CiscSortedLinkedList > implements CiscList { /** * A reference to this list's dummy node. Its next reference should refer to the node containing the first element * in this list, or it should refer to itself if the list is empty. The next reference within the node containing * the last element in this list should refer to dummy, thus creating a cyclic list. */ private Node dummy; /** * Number of elements in the list. */ private int size; /** * Constructs an empty CiscSortedLinkedList instance with a non-null dummy node whose next reference refers to * itself. */ public CiscSortedLinkedList() { dummy = new Node<>(null, null); dummy.next = dummy; } /** * Returns the number of elements in this list. * * @return the number of elements in this list */ @Override public int size() { return size; } /** * Returns {@code true} if this list contains no elements. * * @return {@code true} if this list contains no elements */ @Override public boolean isEmpty() { return size==0; } /** * Returns {@code true} if this list contains the specified element (compared using the {@code equals} method). * This implementation should stop searching as soon as it is able to determine that the specified element is not * present. * * @param o element whose presence in this list is to be tested * @return {@code true} if this list contains the specified element * @throws NullPointerException if the specified element is null */ @Override public boolean contains(Object o) { if(o==null){ throw new NullPointerException(); } return containsHelper(o,dummy.next); } private boolean containsHelper(Object o, Node node){ if(node== dummy){ return false; } else if(o.equals(node.data)){ return true; } else{ return containsHelper(o,node.next); } } /** * Returns an iterator over the elements in this list in proper sequence. * * @return an iterator over the elements in this list in proper sequence */ @Override public Iterator iterator() { //return new Iterator (){ //private Node curr = dummy.next; //private Node prev = dummy; //private boolean canRemove = false; return null; } /** * Returns an array containing all of the elements in this list in proper sequence (from first to last element). *
The returned array will be "safe" in that no references to it are maintained by this list. (In other words, * this method must allocate a new array even if this list is backed by an array). The caller is thus free to modify * the returned array. * * @return an array containing all of the elements in this list in proper sequence */ @Override public Object[] toArray() { Object[] arr = new Object[size]; int i = 0; for(Node current = dummy;current!=null;cur.
Describe an algorithm for concatenating two singly linked lists L and.pdfdeepak596396
Dataset:
https://docs.google.com/spreadsheets/d/1NxuGt4LJ3ofi2PaWLWpAl90JmfqMKcGV/edit?usp=sharing&ouid=111109979069524025260&rtpof=true&sd=true
Q1) What is the average tenure of those customers of the telecom operator who are still with the
company as a customer and also those who have stopped using the services provided by the
company? (1 mark)
Here, churn = 'No' means that the customer is currently associated with the company, and churn
= 'Yes' means that the customer has stopped using the services provided by the company.
Q2)What is the monthly average revenue generated by the customers who are with the company
and also those who have left? (1 mark)
Q3) Find the percentage of churn and non-churn customers for each category of the following
services: (4 marks)
-MultipleLines
-PaperlessBilling
-OnlineSecurity
-OnlineBackup
-DeviceProtection
-TechSupport
-StreamingTV
-StreamingMovies.
please i need help Im writing a program to test the merge sort alg.pdfezonesolutions
please i need help I\'m writing a program to test the merge sort algorithm for linked lists.
I need to Print the list before being sorted and the list after sorting the elements
here is my code only help in test program the four classes are ok except the test program.
TEST PROGRAM
import java.io.*;
import java.util.*;
public class Ch9_ProgExercise7 {
Scanner input = new Scanner(System.in);
public static void main(String[] args) throws IOException {
OrderedLinkedList list
= new OrderedLinkedList(); //Line 1
IntElement num = new IntElement(); //Line 2
// Prompt the user to enter some integers
System.out.println(\"Enter integers numbers \");
String temp = input.hasnextLine();
String[] split = temp.split(\" \");
for (int i = 0; i < split.length; i++) {
Integer a = Integer.parseInt(split[i]);
// insert the intgers into the list you created above
num.setNum(a);
list.insertNode(num);
}
System.out.println();
// Print the list before being sorted
// call the mergesort method
System.out.println();
// print the list after sorting the elements
}
}
ORDEREDLICKEDLIST CLASS
public class OrderedLinkedList extends LinkedListClass
{
//default constructor
public OrderedLinkedList()
{
super();
}
//copy constructor
public OrderedLinkedList(OrderedLinkedList otherList)
{
super(otherList);
}
public void linkedInsertionSort()
{
LinkedListNode lastInOrder;
LinkedListNode firstOutOfOrder;
LinkedListNode current;
LinkedListNode trailCurrent;
lastInOrder = first;
if(first == null)
System.out.println(\"Cannot sort an empty list\");
else
if(first.link == null)
System.out.println(\"The list is of length 1. \"
+ \"Already in order\");
else
while(lastInOrder.link != null)
{
firstOutOfOrder = lastInOrder.link;
if(firstOutOfOrder.info.compareTo(first.info) < 0)
{
lastInOrder.link = firstOutOfOrder.link;
firstOutOfOrder.link = first;
first = firstOutOfOrder;
}
else
{
trailCurrent = first;
current = first.link;
while(current.info.compareTo(firstOutOfOrder.info) < 0)
{
trailCurrent = current;
current = current.link;
}
if(current != firstOutOfOrder)
{
lastInOrder.link = firstOutOfOrder.link;
firstOutOfOrder.link = current;
trailCurrent.link = firstOutOfOrder;
}
else
lastInOrder = lastInOrder.link;
}
}
}//end linkedInsertionSort
//Method to determine whether searchItem is in
//the list.
//Postcondition: Returns true if searchItem is found
// in the list; otherwise, it returns
// false.
public boolean search(DataElement searchItem)
{
LinkedListNode current; //variable to traverse the list
boolean found;
current = first; //set current to point to the first
//node in the list
found = false; //set found to false
while(current != null && !found ) //search the list
if(current.info.compareTo(searchItem) >= 0)
found = true;
else
current = current.link; //make current point to
//the next node
if(found)
found = current.info.equals(searchItem);
return found;
}
//Method to insert insertItem in the list
//Postcondition: first points to the new list,
// newItem is inserted at the proper place
//.
Note- Can someone help me with the Public boolean add(E value) method.pdfStewart29UReesa
Note: Can someone help me with the Public boolean add(E value) method and Private void
add(E value,Node n) method. I have everything but it is not working. Also need help with the
remove methods. Both public and private methods for remove. package edu.ust.cisc; import
java.util.Iterator; import java.util.NoSuchElementException; public class CiscSortedLinkedList
> implements CiscList { /** * A reference to this list's dummy node. Its next reference should
refer to the node containing the first element * in this list, or it should refer to itself if the list is
empty. The next reference within the node containing * the last element in this list should refer to
dummy, thus creating a cyclic list. */ private Node dummy; /** * Number of elements in the list.
*/ private int size; /** * Constructs an empty CiscSortedLinkedList instance with a non-null
dummy node whose next reference refers to * itself. */ public CiscSortedLinkedList() { dummy
= new Node<>(null, null); dummy.next = dummy; } /** * Returns the number of elements in
this list. * * @return the number of elements in this list */ @Override public int size() { return
size; } /** * Returns {@code true} if this list contains no elements. * * @return {@code true} if
this list contains no elements */ @Override public boolean isEmpty() { return size==0; } /** *
Returns {@code true} if this list contains the specified element (compared using the {@code
equals} method). * This implementation should stop searching as soon as it is able to determine
that the specified element is not * present. * @param o element whose presence in this list is to
be tested * @return {@code true} if this list contains the specified element * @throws
NullPointerException if the specified element is null */ @Override public boolean
contains(Object o) { if(o==null){ throw new NullPointerException(); } return
containsHelper(o,dummy.next); } private boolean containsHelper(Object o, Node node){
if(node== dummy){ return false; } else if(o.equals(node.data)){ return true; } else{ return
containsHelper(o,node.next); } } /** * Returns an iterator over the elements in this list in proper
sequence. * * @return an iterator over the elements in this list in proper sequence */ @Override
public Iterator iterator() { //return new Iterator (){ //private Node curr = dummy.next; //private
Node prev = dummy; //private boolean canRemove = false; return new CiscLinkedListIterator();
} /** * Returns an array containing all of the elements in this list in proper sequence (from first
to last element). * *
The returned array will be "safe" in that no references to it are maintained by this list. (In other
words, * this method must allocate a new array even if this list is backed by an array). The caller
is thus free to modify * the returned array. * * @return an array containing all of the elements in
this list in proper sequence */ @Override public Object[] toArray() { Object[] arr = new
Object[size]; int i = 0; for(Node current = dummy;curren.
Problem- Describe an algorithm for concatenating two singly linked lis.pdfJamesPXNNewmanp
Problem: Describe an algorithm for concatenating two singly linked lists L and M, into a single
list L that contains all the nodes of L followed by all the nodes of M.
Modify the SinglyLinkedList class to contain the method:
public void concatenate(SinglyLinkedList other) { ... }
---------------Below is the code--------------------
public class SinglyLinkedList<E> implements Cloneable {
//---------------- nested Node class ----------------
/**
* Node of a singly linked list, which stores a reference to its
* element and to the subsequent node in the list (or null if this
* is the last node).
*/
private static class Node<E> {
/** The element stored at this node */
private E element; // reference to the element stored at this node
/** A reference to the subsequent node in the list */
private Node<E> next; // reference to the subsequent node in the list
/**
* Creates a node with the given element and next node.
*
* @param e the element to be stored
* @param n reference to a node that should follow the new node
*/
public Node(E e, Node<E> n) {
element = e;
next = n;
}
// Accessor methods
/**
* Returns the element stored at the node.
* @return the element stored at the node
*/
public E getElement() { return element; }
/**
* Returns the node that follows this one (or null if no such node).
* @return the following node
*/
public Node<E> getNext() { return next; }
// Modifier methods
/**
* Sets the node's next reference to point to Node n.
* @param n the node that should follow this one
*/
public void setNext(Node<E> n) { next = n; }
} //----------- end of nested Node class -----------
// instance variables of the SinglyLinkedList
/** The head node of the list */
private Node<E> head = null; // head node of the list (or null if empty)
/** The last node of the list */
private Node<E> tail = null; // last node of the list (or null if empty)
/** Number of nodes in the list */
private int size = 0; // number of nodes in the list
/** Constructs an initially empty list. */
public SinglyLinkedList() { } // constructs an initially empty list
// access methods
/**
* Returns the number of elements in the linked list.
* @return number of elements in the linked list
*/
public int size() { return size; }
/**
* Tests whether the linked list is empty.
* @return true if the linked list is empty, false otherwise
*/
public boolean isEmpty() { return size == 0; }
/**
* Returns (but does not remove) the first element of the list
* @return element at the front of the list (or null if empty)
*/
public E first() { // returns (but does not remove) the first element
if (isEmpty()) return null;
return head.getElement();
}
/**
* Returns (but does not remove) the last element of the list.
* @return element at the end of the list (or null if empty)
*/
public E last() { // returns (but does not remove) the last element
if (isEmpty()) return null;
return tail.getElement();
}
// update methods
/**
* Adds an element to the front of the list.
* @param e the new element to add
*/
publ.
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.
Problem- Describe an algorithm for concatenating two singly linked lis.pdfkingsandqueens3
Problem: Describe an algorithm for concatenating two singly linked lists L and M, into a single
list L that contains all the nodes of L followed by all the nodes of M. Modify the
SinglyLinkedList class to contain the method:
public void concatenate(SinglyLinkedList other) { ... }
PLEASE PLEASE USE THE CODE BELOW..... THANK YOU
public class SinglyLinkedList<E> implements Cloneable {
//---------------- nested Node class ----------------
/**
* Node of a singly linked list, which stores a reference to its
* element and to the subsequent node in the list (or null if this
* is the last node).
*/
private static class Node<E> {
/** The element stored at this node */
private E element; // reference to the element stored at this node
/** A reference to the subsequent node in the list */
private Node<E> next; // reference to the subsequent node in the list
/**
* Creates a node with the given element and next node.
*
* @param e the element to be stored
* @param n reference to a node that should follow the new node
*/
public Node(E e, Node<E> n) {
element = e;
next = n;
}
// Accessor methods
/**
* Returns the element stored at the node.
* @return the element stored at the node
*/
public E getElement() { return element; }
/**
* Returns the node that follows this one (or null if no such node).
* @return the following node
*/
public Node<E> getNext() { return next; }
// Modifier methods
/**
* Sets the node's next reference to point to Node n.
* @param n the node that should follow this one
*/
public void setNext(Node<E> n) { next = n; }
} //----------- end of nested Node class -----------
// instance variables of the SinglyLinkedList
/** The head node of the list */
private Node<E> head = null; // head node of the list (or null if empty)
/** The last node of the list */
private Node<E> tail = null; // last node of the list (or null if empty)
/** Number of nodes in the list */
private int size = 0; // number of nodes in the list
/** Constructs an initially empty list. */
public SinglyLinkedList() { } // constructs an initially empty list
// access methods
/**
* Returns the number of elements in the linked list.
* @return number of elements in the linked list
*/
public int size() { return size; }
/**
* Tests whether the linked list is empty.
* @return true if the linked list is empty, false otherwise
*/
public boolean isEmpty() { return size == 0; }
/**
* Returns (but does not remove) the first element of the list
* @return element at the front of the list (or null if empty)
*/
public E first() { // returns (but does not remove) the first element
if (isEmpty()) return null;
return head.getElement();
}
/**
* Returns (but does not remove) the last element of the list.
* @return element at the end of the list (or null if empty)
*/
public E last() { // returns (but does not remove) the last element
if (isEmpty()) return null;
return tail.getElement();
}
// update methods
/**
* Adds an element to the front of the list.
* @param e the new element to add
*/
public vo.
import java.util.Iterator; import java.util.NoSuchElementException; /** * An implementation
of MyList with a linked list (a longer exercise would be to * implement the List interface as is
done in the class java.util.LinkedList: * the source of the LinkedList class is available from Sun.
Check it out). */ public class MyLinkedList implements MyList { // A private class to
represent a Node in the linked list private class Node { public E item;
public Node next; // a convenient constructor public Node(E o) {
this.item = o; this.next = null; } } // The start of the linked
list private Node head; // The last Node in the linked list private Node tail;
// Number of elements in the list private int size; /** * Creates an empty list (this
constructor is not necessary) */ public MyLinkedList() { } /** *
Returns the number of elements in this list. */ public int size() { return size;
} /** * Returns true if this list contains no elements. */ public boolean
isEmpty() { return size == 0; } /** * Appends the specified element to
the end of this list */ public boolean add(E o) { Node n = new Node(o);
// If this is the first element in the list if (head == null) { head = n;
} else { // If the list is not empty, use tail tail.next = n;
} // update tail tail = n; // update size size++;
return true; } /** * Empties this List */ public void clear() {
// update head, tail and size head = tail = null; size = 0; } /**
* Returns the element at the specified position in this list. */ public E get(int index) {
if (index < 0 || index >= size) { throw new
IndexOutOfBoundsException(\"index = \" + index); } // Find it
Node n = head; for (int i = 0; i < index; i++) { n = n.next; }
return n.item; } /** * Returns the index of the specified element (-1 if
there is no match) */ public int indexOf(Object o) { // If o is null
int index = 0; Node p = head; if (o == null) // look for a null element in the
list { while (p != null) { if (p.item == null) {
return index; } index++;
p = p.next; } } else // o is an object (use equals) {
while (p != null) { if (o.equals(p.item)) { return
index; } index++; p = p.next;
} } // if we get here, o is not in the list return -1; }
/** * Returns true if this list contains the specified element. */ public boolean
contains(Object o) { // easy with indexOf return indexOf(o) != -1; }
/** * Removes the element in the List at position index */ public boolean
remove(int index) { if (index < 0 || index >= size) { throw new
IndexOutOfBoundsException(\"index = \" + index); } // Find the
corresponding node Node prev = null, p = head; for (int i = 0; i < index; i++)
{ prev = p; p = p.next; } // Remove it
// Special case for the first node if (p == head) { head = head.next;
} else { prev.next = p.next; } // If the last node has been
removed, update tail if (p == tail) { tail = prev; } //
update size size--; return true; } /** * Removes the element
in the List at position index */ public boolean remove(Object o) { // easy
with indexOf and remove int index = i.
Note- Can someone help me with the private E get(int index- int curren (1).docxVictorzH8Bondx
Note: Can someone help me with the private E get(int index, int currentIndex, Node n)method. The code is not running. Also I need help with the public void add(int index, E element) method too. Please use the parameters provided with the code to solve. package edu.ust.cisc; import java.util.Iterator; import java.util.NoSuchElementException; public class CiscSortedLinkedList > implements CiscList { /** * A reference to this list's dummy node. Its next reference should refer to the node containing the first element * in this list, or it should refer to itself if the list is empty. The next reference within the node containing * the last element in this list should refer to dummy, thus creating a cyclic list. */ private Node dummy; /** * Number of elements in the list. */ private int size; /** * Constructs an empty CiscSortedLinkedList instance with a non-null dummy node whose next reference refers to * itself. */ public CiscSortedLinkedList() { dummy = new Node<>(null, null); dummy.next = dummy; } /** * Returns the number of elements in this list. * * @return the number of elements in this list */ @Override public int size() { return size; } /** * Returns {@code true} if this list contains no elements. * * @return {@code true} if this list contains no elements */ @Override public boolean isEmpty() { return size==0; } /** * Returns {@code true} if this list contains the specified element (compared using the {@code equals} method). * This implementation should stop searching as soon as it is able to determine that the specified element is not * present. * * @param o element whose presence in this list is to be tested * @return {@code true} if this list contains the specified element * @throws NullPointerException if the specified element is null */ @Override public boolean contains(Object o) { if(o==null){ throw new NullPointerException(); } return containsHelper(o,dummy.next); } private boolean containsHelper(Object o, Node node){ if(node== dummy){ return false; } else if(o.equals(node.data)){ return true; } else{ return containsHelper(o,node.next); } } /** * Returns an iterator over the elements in this list in proper sequence. * * @return an iterator over the elements in this list in proper sequence */ @Override public Iterator iterator() { //return new Iterator (){ //private Node curr = dummy.next; //private Node prev = dummy; //private boolean canRemove = false; return null; } /** * Returns an array containing all of the elements in this list in proper sequence (from first to last element). *
The returned array will be "safe" in that no references to it are maintained by this list. (In other words, * this method must allocate a new array even if this list is backed by an array). The caller is thus free to modify * the returned array. * * @return an array containing all of the elements in this list in proper sequence */ @Override public Object[] toArray() { Object[] arr = new Object[size]; int i = 0; for(Node current = dummy;current!=null;cur.
Describe an algorithm for concatenating two singly linked lists L and.pdfdeepak596396
Dataset:
https://docs.google.com/spreadsheets/d/1NxuGt4LJ3ofi2PaWLWpAl90JmfqMKcGV/edit?usp=sharing&ouid=111109979069524025260&rtpof=true&sd=true
Q1) What is the average tenure of those customers of the telecom operator who are still with the
company as a customer and also those who have stopped using the services provided by the
company? (1 mark)
Here, churn = 'No' means that the customer is currently associated with the company, and churn
= 'Yes' means that the customer has stopped using the services provided by the company.
Q2)What is the monthly average revenue generated by the customers who are with the company
and also those who have left? (1 mark)
Q3) Find the percentage of churn and non-churn customers for each category of the following
services: (4 marks)
-MultipleLines
-PaperlessBilling
-OnlineSecurity
-OnlineBackup
-DeviceProtection
-TechSupport
-StreamingTV
-StreamingMovies.
please i need help Im writing a program to test the merge sort alg.pdfezonesolutions
please i need help I\'m writing a program to test the merge sort algorithm for linked lists.
I need to Print the list before being sorted and the list after sorting the elements
here is my code only help in test program the four classes are ok except the test program.
TEST PROGRAM
import java.io.*;
import java.util.*;
public class Ch9_ProgExercise7 {
Scanner input = new Scanner(System.in);
public static void main(String[] args) throws IOException {
OrderedLinkedList list
= new OrderedLinkedList(); //Line 1
IntElement num = new IntElement(); //Line 2
// Prompt the user to enter some integers
System.out.println(\"Enter integers numbers \");
String temp = input.hasnextLine();
String[] split = temp.split(\" \");
for (int i = 0; i < split.length; i++) {
Integer a = Integer.parseInt(split[i]);
// insert the intgers into the list you created above
num.setNum(a);
list.insertNode(num);
}
System.out.println();
// Print the list before being sorted
// call the mergesort method
System.out.println();
// print the list after sorting the elements
}
}
ORDEREDLICKEDLIST CLASS
public class OrderedLinkedList extends LinkedListClass
{
//default constructor
public OrderedLinkedList()
{
super();
}
//copy constructor
public OrderedLinkedList(OrderedLinkedList otherList)
{
super(otherList);
}
public void linkedInsertionSort()
{
LinkedListNode lastInOrder;
LinkedListNode firstOutOfOrder;
LinkedListNode current;
LinkedListNode trailCurrent;
lastInOrder = first;
if(first == null)
System.out.println(\"Cannot sort an empty list\");
else
if(first.link == null)
System.out.println(\"The list is of length 1. \"
+ \"Already in order\");
else
while(lastInOrder.link != null)
{
firstOutOfOrder = lastInOrder.link;
if(firstOutOfOrder.info.compareTo(first.info) < 0)
{
lastInOrder.link = firstOutOfOrder.link;
firstOutOfOrder.link = first;
first = firstOutOfOrder;
}
else
{
trailCurrent = first;
current = first.link;
while(current.info.compareTo(firstOutOfOrder.info) < 0)
{
trailCurrent = current;
current = current.link;
}
if(current != firstOutOfOrder)
{
lastInOrder.link = firstOutOfOrder.link;
firstOutOfOrder.link = current;
trailCurrent.link = firstOutOfOrder;
}
else
lastInOrder = lastInOrder.link;
}
}
}//end linkedInsertionSort
//Method to determine whether searchItem is in
//the list.
//Postcondition: Returns true if searchItem is found
// in the list; otherwise, it returns
// false.
public boolean search(DataElement searchItem)
{
LinkedListNode current; //variable to traverse the list
boolean found;
current = first; //set current to point to the first
//node in the list
found = false; //set found to false
while(current != null && !found ) //search the list
if(current.info.compareTo(searchItem) >= 0)
found = true;
else
current = current.link; //make current point to
//the next node
if(found)
found = current.info.equals(searchItem);
return found;
}
//Method to insert insertItem in the list
//Postcondition: first points to the new list,
// newItem is inserted at the proper place
//.
Note- Can someone help me with the Public boolean add(E value) method.pdfStewart29UReesa
Note: Can someone help me with the Public boolean add(E value) method and Private void
add(E value,Node n) method. I have everything but it is not working. Also need help with the
remove methods. Both public and private methods for remove. package edu.ust.cisc; import
java.util.Iterator; import java.util.NoSuchElementException; public class CiscSortedLinkedList
> implements CiscList { /** * A reference to this list's dummy node. Its next reference should
refer to the node containing the first element * in this list, or it should refer to itself if the list is
empty. The next reference within the node containing * the last element in this list should refer to
dummy, thus creating a cyclic list. */ private Node dummy; /** * Number of elements in the list.
*/ private int size; /** * Constructs an empty CiscSortedLinkedList instance with a non-null
dummy node whose next reference refers to * itself. */ public CiscSortedLinkedList() { dummy
= new Node<>(null, null); dummy.next = dummy; } /** * Returns the number of elements in
this list. * * @return the number of elements in this list */ @Override public int size() { return
size; } /** * Returns {@code true} if this list contains no elements. * * @return {@code true} if
this list contains no elements */ @Override public boolean isEmpty() { return size==0; } /** *
Returns {@code true} if this list contains the specified element (compared using the {@code
equals} method). * This implementation should stop searching as soon as it is able to determine
that the specified element is not * present. * @param o element whose presence in this list is to
be tested * @return {@code true} if this list contains the specified element * @throws
NullPointerException if the specified element is null */ @Override public boolean
contains(Object o) { if(o==null){ throw new NullPointerException(); } return
containsHelper(o,dummy.next); } private boolean containsHelper(Object o, Node node){
if(node== dummy){ return false; } else if(o.equals(node.data)){ return true; } else{ return
containsHelper(o,node.next); } } /** * Returns an iterator over the elements in this list in proper
sequence. * * @return an iterator over the elements in this list in proper sequence */ @Override
public Iterator iterator() { //return new Iterator (){ //private Node curr = dummy.next; //private
Node prev = dummy; //private boolean canRemove = false; return new CiscLinkedListIterator();
} /** * Returns an array containing all of the elements in this list in proper sequence (from first
to last element). * *
The returned array will be "safe" in that no references to it are maintained by this list. (In other
words, * this method must allocate a new array even if this list is backed by an array). The caller
is thus free to modify * the returned array. * * @return an array containing all of the elements in
this list in proper sequence */ @Override public Object[] toArray() { Object[] arr = new
Object[size]; int i = 0; for(Node current = dummy;curren.
Problem- Describe an algorithm for concatenating two singly linked lis.pdfJamesPXNNewmanp
Problem: Describe an algorithm for concatenating two singly linked lists L and M, into a single
list L that contains all the nodes of L followed by all the nodes of M.
Modify the SinglyLinkedList class to contain the method:
public void concatenate(SinglyLinkedList other) { ... }
---------------Below is the code--------------------
public class SinglyLinkedList<E> implements Cloneable {
//---------------- nested Node class ----------------
/**
* Node of a singly linked list, which stores a reference to its
* element and to the subsequent node in the list (or null if this
* is the last node).
*/
private static class Node<E> {
/** The element stored at this node */
private E element; // reference to the element stored at this node
/** A reference to the subsequent node in the list */
private Node<E> next; // reference to the subsequent node in the list
/**
* Creates a node with the given element and next node.
*
* @param e the element to be stored
* @param n reference to a node that should follow the new node
*/
public Node(E e, Node<E> n) {
element = e;
next = n;
}
// Accessor methods
/**
* Returns the element stored at the node.
* @return the element stored at the node
*/
public E getElement() { return element; }
/**
* Returns the node that follows this one (or null if no such node).
* @return the following node
*/
public Node<E> getNext() { return next; }
// Modifier methods
/**
* Sets the node's next reference to point to Node n.
* @param n the node that should follow this one
*/
public void setNext(Node<E> n) { next = n; }
} //----------- end of nested Node class -----------
// instance variables of the SinglyLinkedList
/** The head node of the list */
private Node<E> head = null; // head node of the list (or null if empty)
/** The last node of the list */
private Node<E> tail = null; // last node of the list (or null if empty)
/** Number of nodes in the list */
private int size = 0; // number of nodes in the list
/** Constructs an initially empty list. */
public SinglyLinkedList() { } // constructs an initially empty list
// access methods
/**
* Returns the number of elements in the linked list.
* @return number of elements in the linked list
*/
public int size() { return size; }
/**
* Tests whether the linked list is empty.
* @return true if the linked list is empty, false otherwise
*/
public boolean isEmpty() { return size == 0; }
/**
* Returns (but does not remove) the first element of the list
* @return element at the front of the list (or null if empty)
*/
public E first() { // returns (but does not remove) the first element
if (isEmpty()) return null;
return head.getElement();
}
/**
* Returns (but does not remove) the last element of the list.
* @return element at the end of the list (or null if empty)
*/
public E last() { // returns (but does not remove) the last element
if (isEmpty()) return null;
return tail.getElement();
}
// update methods
/**
* Adds an element to the front of the list.
* @param e the new element to add
*/
publ.
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.
Problem- Describe an algorithm for concatenating two singly linked lis.pdfkingsandqueens3
Problem: Describe an algorithm for concatenating two singly linked lists L and M, into a single
list L that contains all the nodes of L followed by all the nodes of M. Modify the
SinglyLinkedList class to contain the method:
public void concatenate(SinglyLinkedList other) { ... }
PLEASE PLEASE USE THE CODE BELOW..... THANK YOU
public class SinglyLinkedList<E> implements Cloneable {
//---------------- nested Node class ----------------
/**
* Node of a singly linked list, which stores a reference to its
* element and to the subsequent node in the list (or null if this
* is the last node).
*/
private static class Node<E> {
/** The element stored at this node */
private E element; // reference to the element stored at this node
/** A reference to the subsequent node in the list */
private Node<E> next; // reference to the subsequent node in the list
/**
* Creates a node with the given element and next node.
*
* @param e the element to be stored
* @param n reference to a node that should follow the new node
*/
public Node(E e, Node<E> n) {
element = e;
next = n;
}
// Accessor methods
/**
* Returns the element stored at the node.
* @return the element stored at the node
*/
public E getElement() { return element; }
/**
* Returns the node that follows this one (or null if no such node).
* @return the following node
*/
public Node<E> getNext() { return next; }
// Modifier methods
/**
* Sets the node's next reference to point to Node n.
* @param n the node that should follow this one
*/
public void setNext(Node<E> n) { next = n; }
} //----------- end of nested Node class -----------
// instance variables of the SinglyLinkedList
/** The head node of the list */
private Node<E> head = null; // head node of the list (or null if empty)
/** The last node of the list */
private Node<E> tail = null; // last node of the list (or null if empty)
/** Number of nodes in the list */
private int size = 0; // number of nodes in the list
/** Constructs an initially empty list. */
public SinglyLinkedList() { } // constructs an initially empty list
// access methods
/**
* Returns the number of elements in the linked list.
* @return number of elements in the linked list
*/
public int size() { return size; }
/**
* Tests whether the linked list is empty.
* @return true if the linked list is empty, false otherwise
*/
public boolean isEmpty() { return size == 0; }
/**
* Returns (but does not remove) the first element of the list
* @return element at the front of the list (or null if empty)
*/
public E first() { // returns (but does not remove) the first element
if (isEmpty()) return null;
return head.getElement();
}
/**
* Returns (but does not remove) the last element of the list.
* @return element at the end of the list (or null if empty)
*/
public E last() { // returns (but does not remove) the last element
if (isEmpty()) return null;
return tail.getElement();
}
// update methods
/**
* Adds an element to the front of the list.
* @param e the new element to add
*/
public vo.
Data Structures in C++I am really new to C++, so links are really .pdfrohit219406
Data Structures in C++
I am really new to C++, so links are really hard topic for me. It would be nice if you can provide
explanations of what doubly linked lists are and of some of you steps... Thank you
In this assignment, you will implement a doubly-linked list class, together with some list
operations. To make things easier, you’ll implement a list of int, rather than a template class.
Solution
A variable helps us to identify the data. For ex: int a = 5; Here 5 is identified through variable a.
Now, if we have collection of integers, we need some representation to identify them. We call it
array. For ex: int arr[5]
This array is nothing but a Data Structure.
So, a Data Structure is a way to group the data.
There are many Data Structures available like Arrays, Linked List, Doubly-Linked list, Stack,
Queue, etc.
Doubly-Linked list are the ones where you can traverse from the current node both in left and
right directions.
Why so many different types of Data Structures are required ?
Answer is very simple, grouping of data, storage of data and accessing the data is different.
For example, in case of Arrays we store all the data in contiguous locations.
What if we are not able to store the data in contiguous locations because we have huge data.
Answer is go for Linked List/Doubly-Linked list.
Here we can store the data anywhere and link the data through pointers.
I will try to provide comments for the code you have given. May be this can help you.
#pragma once
/*
dlist.h
Doubly-linked lists of ints
*/
#include
class dlist {
public:
dlist() { }
// Here we are creating a NODE, it has a integer value and two pointers.
// One pointer is to move to next node and other to go back to previous node.
struct node {
int value;
node* next;
node* prev;
};
// To return head pointer, i.e. start of the Doubly-Linked list.
node* head() const { return _head; }
// To return Tail pointer, i.e. end of the Doubly-Linked list.
node* tail() const { return _tail; }
// **** Implement ALL the following methods ****
// Returns the node at a particular index (0 is the head).
node* at(int index){
int cnt = 0;
struct node* tmp = head();
while(tmp!=NULL)
{
if (cnt+1 == index)
return tmp;
tmp = tmp->next;
}
}
// Insert a new value, after an existing one
void insert(node *previous, int value){
// check if the given previous is NULL
if (previous == NULL)
{
printf(\"the given previous node cannot be NULL\");
return;
}
// allocate new node
struct node* new_node =(struct node*) malloc(sizeof(struct node));
// put in the data
new_node->data = new_data;
// Make next of new node as next of previous
new_node->next = previous->next;
// Make the next of previous as new_node
previous->next = new_node;
// Make previous as previous of new_node
new_node->prev = previous;
// Change previous of new_node\'s next node
if (new_node->next != NULL)
new_node->next->prev = new_node;
}
// Delete the given node
void del(node* which){
struct node* head_ref = head();
/* base case */
if(*head_ref == NUL.
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.
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 =.
public class MyLinkedListltE extends ComparableltEgtg.pdfaccostinternational
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++; // Increase size
}
public void add(int index, E e) {
if (index == 0) {
addFirst(e);
}
else if (index >= size) {
addLast(e);
}
else {
Node<E> current = head;
for (int i = 1; i < index; i++) {
current = current.next;
}
Node<E> temp = current.next;
current.next = new Node<>(e);
(current.next).next = temp;
size++;
}
}
//Add e to the end of this linkedlist
public void add(E e) {
// Left as Exercise
}
/** Remove the head node and
* return the object that is contained in the removed node. */
public E removeFirst() {
if (size == 0) {
return null;
}
else {
E temp = head.element;
head = head.next;
size--;
if (head == null) {
tail = null;
}
return temp;
}
}
/** Remove the last node and
* return the object that is contained in the removed node. */
public E removeLast() {
if (size == 0) {
return null;
}
else if (size == 1) {
E temp = head.element;
head = tail = null;
size = 0;
return temp;
}
else {
Node<E> current = head;
for (int i = 0; i < size - 2; i++) {
current = current.next;
}
E temp = tail.element;
tail = current;
tail.next = null;
size--;
return temp;
}
}
/** Remove the element at the specified position in this
* list. Return the element that was removed from the list. */
public E remove(int index) {
if (index < 0 || index >= size) {
return null;
}
else if (index == 0) {
return removeFirst();
}
else if (index == size - 1) {
return removeLast();
}
else {
Node<E> previous = head;
for (int i = 1; i < index; i++) {
previous = previous.next;
}
Node<E> current = previous.next;
previous.next = current.next;
size--;
return current.element;
}
}
/** Clear the list */
public void clear() {
size = 0;
head = tail = null;
}
/** Override toString() to return elements in the list in [] separated by , */
public String toString() {
StringBuilder result = new StringBuilder("[");
Node<E> current = head;
for (int i = 0; i < size; i++) {
result.append(current..
Class DiagramIn the Assignment #10, you are given three files Ass.pdfxlynettalampleyxc
Class Diagram:
In the Assignment #10, you are given three files Assignment10.java, LinkedList.java, and
ListIterator.java. You will need to add additional methods in the LinkedList class in the
LinkedList.java file. The LinkedList will be tested using strings only.
Specifically, the following methods must be implemented in the LinkedList class:
(You should utilize listIterator() method already defined in the LinkedList class to obtain its
LinkedListIterator object, and use the methods in the LinkedListIterator class to traverse from
the first element to the last element of the linked list to define the following methods.)
1.
public String toString()
The toString method should concatenate strings in the linked list, and return a string of the
following format:
{ Apple Banana Melon Orange }
Thus it starts with \"{\" and ends with \"}\", and there is a space between strings and \"{\" or
\"}\". If the list is empty, it returns \"{ }\" with a space in between.
2.
public boolean isEmpty()
The isEmpty method returns true of the linked list is empty, false otherwise.
3.
public void addElement(Object element)
The addElement adds the parameter element at the parameter in the linked list in alphabetical
order. For instance, if the linked list contains {Apple, Banana, Grape}, and a user tries to add
\"Carrot\", then it should be added as:
{Apple, Banana, Carrot, Grape}.
4.
public Object removeElement(int index)
The removeElement removes the string (Object) at the parameter index and returns it. Note that
this index starts with 0 just like array indices. For instance, if the linked list contains {Apple,
Banana, Carrot, Grape} and the parameter index is 3, then \"Grape\" should be remove. If the
parameter index is larger or smaller than the existing indices, it should throw an object of the
IndexOutOfBoundsException class (and the content of the linked list should remain unchanged).
5.
public Object getElement(int index)
The getElement searches the string (Object) at the parameter index and returns it. Note that this
index starts with 0 just like array indices. For instance, if the linked list contains {Apple, Banana,
Carrot, Grape} and the parameter index is 3, then \"Grape\" will be returned. If the parameter
index is larger or smaller than the existing indices, it should throw an object of the
IndexOutOfBoundsException class (and the content of the linked list should remain unchanged).
6.
public void searchAndReplace(Object oldString, Object newString)
The searchAndReplace method searches all occurrences of the first parameter string (object) in
the list, and replaces them with the second parameter string (object). If the parameter string does
not exist in the linked list, then the linked list content will not change.
7.
public int indexOfLast(Object searchString)
The indexOfLast searches the parameter string (object) with the largest index, and returns its
index. If the parameter string does not exist in the linked list, then it should return -1.
For i.
Please complete all the code as per instructions in Java programming.docxcgraciela1
Please complete all the code as per instructions in Java programming import org.w3c.dom.Node; import javax.xml.crypto.NodeSetData; import java.awt.*; import java.util.Iterator; import java.util.NoSuchElementException; /** * This class implements an acyclic (non-cyclic), doubly-linked list. * @param */ public class CiscDoublyLinkedList implements CiscList { /** * A reference to the first node in the list (or null if list is empty). */ private Node head; /** * A reference to the last node int the list (or null if list is empty). */ private Node tail; /** * Number of elements in the list. */ private int size; /** * Returns the number of elements in this list. * * * @return the number of elements in this list */ @Override public int size() { return size; } /** * Returns {@code true} if this list contains no elements. * * * @return {@code true} if this list contains no elements */ @Override public boolean isEmpty() { if (size == 0){ return true; } return false; } /** * Returns {@code true} if this list contains the specified element (compared using the {@code equals} method). * * * @param o element whose presence in this list is to be tested * @return {@code true} if this list contains the specified element * @throws NullPointerException if the specified element is null */ @Override public boolean contains(Object o) { if(o == null) { throw new NullPointerException(); } Node node = head; while(node != null) { if(node.data.equals(o)){ return true; } node = node.next; } return false; } /** * Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not * contain the element (compared using the {@code equals} method). * * * @param o element to search for * @return the index of the first occurrence of the specified element in this list, or -1 if this list does not * contain the element * @throws NullPointerException if the specified element is null */ @Override public int indexOf(Object o) { if (o == null){ throw new NullPointerException(); } for(int i =0; i = size){ throw new IndexOutOfBoundsException(); } return null; } /** * Appends the specified element to the end of this list. * * *
Lists may place the specified element at arbitrary locations if desired. In particular, an ordered list will * insert the specified element at its sorted location. List classes should clearly specify in their documentation * how elements will be added to the list if different from the default behavior (end of this list). * * @param e element to be appended to this list * @return {@code true} * @throws NullPointerException if the specified element is null */ @Override public boolean add(E e) { if(e == null){ throw new NullPointerException(); } return false; } /** * Replaces the element at the specified position in this list with the specified element. * * * @param index index of the element to replace * @param element element to be stored at the specified position * @return the element previously at the specified position *.
LabProgram.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 ****/
/**
* Instantiates a new LinkedList with default values
* @postcondition
*/
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) {
}
/**** ACCESSORS ****/
/**
* Returns the value stored in the first node
* @precondition <>
* @return the value stored at node first
* @throws NoSuchElementException <>
*/
public T getFirst() throws NoSuchElementException {
if (isEmpty()){
throw new NoSuchElementException("The list is empty");
}
return first.data;
}
/**
* Returns the value stored in the last node
* @precondition <>
* @return the value stored in the node last
* @throws NoSuchElementException <>
*/
public T getLast() throws NoSuchElementException {
if (isEmpty()){
throw new NoSuchElementException("The list is empty");
}
return last.data;
}
/**
* 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 iterator.data;
}
/**
* Returns the current length of the LinkedList
* @return the length of the LinkedList from 0 to n
*/
public int getLength() {
return length;
}
/**
* Returns whether the LinkedList is currently empty
* @return whether the LinkedList is empty
*/
public boolean isEmpty() {
return length == 0;
}
/**
* Returns whether the iterator is offEnd, i.e. null
* @return whether the iterator is null
*/
public boolean offEnd() {
return iterator == null;
}
/**** MUTATORS ****/
/**
* Creates a new first element
* @param data the data to insert at the front of the LinkedList
* @postcondition <>
*/
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++;
}
/**
* Creates a new last element
* @param data the data to insert at the end of the LinkedList
* @postcondition <>
*/
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++;
}
/**
* Inserts a new element after the iterator
* @param data the data to insert
* @precondition
* @throws NullPointerException
*/
public void addIter.
Consider a double-linked linked list implementation with the followin.pdfsales98
Consider a double-linked linked list implementation with the following node: struct Node {int
data; Node *prev; Node *next;} Write a copyList method that is not a member of any class.
The method should take a head pointer and return another pointer. Do not modify the input.
Solution
struct Node {
Node *prev; // previous node
Node *next; // next node
int data; // stored value
};
#include
#include \"List.h\" // std: #include
using namespace std;
typedef DataList ; // std: typedef list Data;
int main() {
Data k;
// back stuff
k.push_back(5);
k.push_back(6);
cout << k.back() << endl;
k.pop_back();
// front stuff
k.push_front(4);
k.push_front(3);
cout << k.front() << endl;
k.pop_front();
// forward iterator
Data::iterator pos;
for (pos = k.begin(); pos != k.end(); ++pos)
cout << *pos << endl;
// output and delete list
while (!k.empty()) {
cout << k.front() << endl;
k.pop_front();
}
k.push_front(5);
k.push_front(6);
// remove and erase
k.remove(5);
pos = k.begin();
k.erase(pos);
k.push_front(5);
k.push_front(6);
// copy constructor
Data l = k;
// assignment operator
Data m;
m = k;
return 0;
}
// List.h
struct Node;
classIterator List;
class List {
public:
typedef ListIterator iterator;
// constructor
List();
// destructor
virtual ~List();
// copy constructor
List(const List& k);
// assignment operator
List& operator=(const List& k);
// insert value in front of list
void push_front(double data);
// insert value in back of list
void push_back(double data);
// delete value from front of list
void pop_front();
// delete value from back of list
void pop_back();
// return value on front of list
double front() const;
// return value on back of list
double back() const;
// delete value specified by iterator
void erase(const iterator& i);
// delete all nodes with specified value
void remove(double data);
// return true if list is empty
bool empty() const;
// return reference to first element in list
iterator begin() const;
// return reference to one past last element in list
iterator end() const;
private:
Node *head; // head of list
};
class ListIterator {
public:
// default constructor
ListIterator() {
i = 0;
}
// construct iterator for given pointer (used for begin/end)
ListIterator(Node *p) {
i = p;
}
// convert iterator to Node*
operator Node*() const {
return i;
}
// test two iterators for not equal
bool operator!=(const ListIterator& k) const {
return i != k.i;
}
// preincrement operator
ListIterator& operator++() {
i = i->next;
return *this;
}
// return value associated with iterator
double& operator*() const {
return i->data;
}
private:
Node *i; // current value of iterator
};
list.cpp
// delete list
static void deleteList(Node *head) {
Node *p = head->next;
while (p != head) {
Node *next = p->next;
delete p;
p = next;
}
delete head;
}
// copy list
static void copyList(const Node *from, Node *&to) {
// create dummy header
to = new Node;
to->next = to->prev = to;
// copy nodes
for (Node *p = from->next; p != from; p = p->next) {
Node *t = new Node;
t.
Design, implement, test(In Java ) a doubly linked list ADT, using DL.pdftrishacolsyn25353
Design, implement, test(In Java ) a doubly linked list ADT, using DLLNode objects as the
nodes. In addition to our standard list operations, your class should provide for backward
iteration through the list. To support this operation, it should export a resetBack method and get a
getPrevious method.To facilitate this, you may want to include an instance variable last that
always references the last element on the list.
DLLNODE.java
public class DLLNode extends LLNode
{
private DLLNode back;
public DLLNode(T info)
{
super(info);
back = null;
}
public void setBack(DLLNode back)
// Sets back link of this DLLNode.
{
this.back = back;
}
public DLLNode getBack()
// Returns back link of this DLLNode.
{
return back;
}
}
LLNODE.java
public class LLNode
{
private LLNode link;
private T info;
public LLNode(T info)
{
this.info = info;
link = null;
}
public void setInfo(T info)
// Sets info of this LLNode.
{
this.info = info;
}
public T getInfo()
// Returns info of this LLONode.
{
return info;
}
public void setLink(LLNode link)
// Sets link of this LLNode.
{
this.link = link;
}
public LLNode getLink()
// Returns link of this LLNode.
{
return link;
}
}
This list can be an unsorted list. My professor suggested to reference off the RefUnsortedList
ADT and modifying it to be a doubly linked list.you need to create resetBack and getPrevious
methods which means you will need another variable to keep track of where you are in the
backward iteration. It is not correct to use currentPos to keep track of the backward iteration, so
make another variable (reference) for this, maybe call it currentBackPos.
RefUnsortedList.java
public class RefUnsortedList implements ListInterface
{
protected int numElements; // number of elements in this list
protected LLNode currentPos; // current position for iteration
// set by find method
protected boolean found; // true if element found, else false
protected LLNode location; // node containing element, if found
protected LLNode previous; // node preceeding location
protected LLNode list; // first node on the list
public RefUnsortedList()
{
numElements = 0;
list = null;
currentPos = null;
}
public void add(T element)
// Adds element to this list.
{
LLNode newNode = new LLNode(element);
newNode.setLink(list);
list = newNode;
numElements++;
}
protected void find(T target)
// Searches list for an occurence of an element e such that
// e.equals(target). If successful, sets instance variables
// found to true, location to node containing e, and previous
// to the node that links to location. If not successful, sets
// found to false.
{
location = list;
found = false;
while (location != null)
{
if (location.getInfo().equals(target)) // if they match
{
found = true;
return;
}
else
{
previous = location;
location = location.getLink();
}
}
}
public int size()
// Returns the number of elements on this list.
{
return numElements;
}
public boolean contains (T element)
// Returns true if this list contains an element e such that
// e.equals(el.
To complete the task, you need to fill in the missing code. I’ve inc.pdfezycolours78
To complete the task, you need to fill in the missing code. I’ve included code to create an
Iterator. An Iterator is an object that iterates over another object – in this case, a circular linked
list. You can use the .next() method to advance the Iterator to the next item (the first time you
call it, the iterator will travel to node at index 0). Using iterator’s .remove() removes the node the
iterator is currently at. Say that we had a CircularLinkedList that looked like this: A ==> B ==>
C ==> D ==> E ==> Calling .next() three times will advance the iterator to index 2. Calling
.remove() once will remove the node at index 2. A ==> B ==> D ==> E ==> Calling .remove()
once more will remove the node now at index 2. A ==> B ==> E ==> The Iterator methods
handle wrapping around the CircularLinkedList. Be sure to create the iterator using l.iterator()
and after you’ve added all the nodes to the list, where l is your CircularLinkedList
Solution
import java.util.Iterator;
class CircularLinkedList implements Iterable {
// Your variables
// You can include a reference to a tail if you want
Node head;
int size; // BE SURE TO KEEP TRACK OF THE SIZE
// implement this constructor
public CircularLinkedList() {
head=null;
}
// writing helper functions for add and remove, like the book did can help
// but remember, the last element\'s next node will be the head!
// attach a node to the end of the list
// Be sure to handle the adding to an empty list
// always returns true
public boolean add(E e) {
Node newNode=new Node(e);
if(size==0){
head=newNode;
}
else{
Node last=getNode(size-1);
last.next=newNode;
}
newNode.next=head; //last element node is set to head
size++;
return true;
}
// need to handle
// out of bounds
// empty list
// adding to front
// adding to middle
// adding to \"end\"
// REMEMBER TO INCREMENT THE SIZE
public boolean add(int index, E e){
if(index>size) return false;
Node tmp=new Node(e);
if(index==0){
tmp.next=head;
Node last=getNode(size-1);
head=tmp;
last.next=head;
}
else {
Node curr=getNode(index-1);
tmp.next=curr.next;
curr.next=tmp;
}
size++;
return true;
}
// I highly recommend using this helper method
// Return Node found at the specified index
// be sure to handle out of bounds cases
private Node getNode(int index ) {
Node prev=head;
for(int i=0;isize) {
e=null;
}
else if(index==0){
e = head.getElement();
Node last=getNode(size-1);
head=head.next;
last.next=head;
size--;
}
else{
Node prev=getNode(index-1);
Node curr=getNode(index);
e=curr.getElement();
prev.next=curr.next;
size--;
}
return e;
}
// Turns your list into a string
// Useful for debugging
public String toString(){
Node current = head;
StringBuilder result = new StringBuilder();
if(size == 0){
return \"\";
}
if(size == 1) {
return head.getElement().toString();
}
else{
do{
result.append(current.getElement());
result.append(\" ==> \");
current = current.next;
} while(current != head);
}
return result.toString();
}
public Iterator iterator() {
return new ListIterator();
}
/.
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.
Homework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdfezzi97
Homework 05 - Linked Lists (C++)
(1) Implement the concepts of a union, and difference as defined noted in Chapter 1 questions 6,
and 8 using a linked list. You should not use arrays, dynamic arrays or the STL vector or STL
list classes.
You will be linking a series of nodes together to implement a single linked list class. Define a
Node as a struct that holds a character (like they did in the book) and a pointer to another Node:
struct Node {
char data;
Node* next;
};
Then define a LinkedList class which has (at a minimum) these member functions:
LinkedList();
~LinkedList();
bool insertAtFront();
bool insertBeforePosition(int index);
bool insertAtBack();
bool deleteAtFront();
bool deleteBeforePosition(int index);
bool deleteAtBack();
Implement each of these functions to provide the correct functionality. These functions return
true if successful in inserting or deleting, otherwise they return false (indicating the operation
was not successful).
Finally, create an overloaded + operator to handle the Union of two linked lists and an
overloaded - operator to handle the Difference of two linked lists.
Because we are dealing with pointers you should have both a LinkedList Constructor and
Destructor. Remember that you do not directly call a Constructor or Destructor Function. The
Destructor is automatically called when the variable loses scope or the program ends.
Remember, that we are dealing with not just one dynamically allocated Node (with the new
operator), but many, so you will have to start at the head of the list and go until the Node points
to nullptr. Then keep deleting the previous Node pointer until there are no Nodes left to delete.
(2) To verify your set class, write a main function that takes two lines of characters from the
input file input.txt and store each line of characters into two separate linked lists. Then using
these two lists, perform the Union and set Difference of the characters from the file, and print the
results to the console.
(3) Please also complete an asymptotic (Big O) analysis of your insertAtFront() and
insertAtBack() member functions. Place this in a file called analysis.txt.
Solution
Here is the complete code for your question. Please do rate the aswer if you are happy with
program. Please read comments in the program. Also pay special attention to comments in + and
- operators. You WILL NEED to comment out if condition in + if you want all elements in both
lists irrespective of if they duplicates or no. For now implemented to have true behaviour of no
duplicates in union.
check the functions by creating some lists and playing around different fucntions like its done in
main and commented out.
As far as complexity:
for insertAtFront() its O(1) since it does not depend on the size of the list. It just replaces the start
of the list. Hence it is O(1) and independent of the size of list.
for insertAtBack(), its O(n) since it depends on the number of elements in the list. It should
traverse till end of list and .
Dividing a linked list into two sublists of almost equal sizesa. A.pdftesmondday29076
Dividing a linked list into two sublists of almost equal sizes
a. Add the operation divideMid to the class linkedListType as follows:
Consider the following statements:
unorderedLinkedList myList;
unorderedLinkedList subList;
Suppose myList points to the list with elements 34 65 27 89 12 (in this order). The statement:
myList.divideMid(subList); divides myList into two sublists: myList points to the list with the
elements 34 65 27,
and subList points to the sublist with the elements 89 12.
b. Write the definition of the function template to implement the operation divideMid. Also,
write a program to test your function. The header files linkedList.h and unorderedLinkedList.h
are supplied. Your test program should produce output similar to this:
Turn in:
linkedList.h with modifications
Your test program.
(C++)
Required code is below:
#ifndef H_UnorderedLinkedList
#define H_UnorderedLinkedList
#include \"linkedList.h\"
using namespace std;
template
class unorderedLinkedList: public linkedListType
{
public:
bool search(const Type& searchItem) const;
//Function to determine whether searchItem is in the list.
//Postcondition: Returns true if searchItem is in the
// list, otherwise the value false is
// returned.
void insertFirst(const Type& newItem);
//Function to insert newItem at the beginning of the list.
//Postcondition: first points to the new list, newItem is
// inserted at the beginning of the list,
// last points to the last node in the
// list, and count is incremented by 1.
void insertLast(const Type& newItem);
//Function to insert newItem at the end of the list.
//Postcondition: first points to the new list, newItem
// is inserted at the end of the list,
// last points to the last node in the
// list, and count is incremented by 1.
void deleteNode(const Type& deleteItem);
//Function to delete deleteItem from the list.
//Postcondition: If found, the node containing
// deleteItem is deleted from the list.
// first points to the first node, last
// points to the last node of the updated
// list, and count is decremented by 1.
};
template
bool unorderedLinkedList::
search(const Type& searchItem) const
{
nodeType *current; //pointer to traverse the list
bool found = false;
current = this->first; //set current to point to the first
//node in the list
while (current != NULL && !found) //search the list
if (current->info == searchItem) //searchItem is found
found = true;
else
current = current->link; //make current point to
//the next node
return found;
}//end search
template
void unorderedLinkedList::insertFirst(const Type& newItem)
{
nodeType *newNode; //pointer to create the new node
newNode = new nodeType; //create the new node
newNode->info = newItem; //store the new item in the node
newNode->link = this->first; //insert newNode before first
this->first = newNode; //make first point to the
//actual first node
this->count++; //increment count
if (this->last == NULL) //if the list was empty, newNode is also
//the last node in the list
this->l.
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdfclimatecontrolsv
PROBLEM STATEMENT:
In this assignment, you will complete DoubleEndedList.java that implements the ListInterface as
well as an interface called DoubleEndedInterface which represents the list's entries by using a
chain of nodes that has both a head reference and a tail reference. Be sure to read through the
code and understand the implementation.
WHAT IS PROVIDED:
- A driver class to test your code. You should not modify this file!
- A list interface (ListInterface.java)
- A double ended interface (DoubleEndedInterface.java)
- An incomplete DoubleEndedList class (DoubleEndedList.java)
WHAT YOU NEED TO DO:
4. Complete the DoubleEndedList class
4. Run the driver and make sure your output is exactly the same as mine (at the bottom of
Driver.java)
\} // end else numberofEntries--; else throw new IndexOut0fBoundsException("Illegal position
given to remove operation."); return result; // Return removed entry }//endreturnreve public T
replace(int givenPosition, T newEntry) \{ T replace(int givenPosition, T newEntry) \{ if
((givenPosition >=1)&& (givenPosition <= numberOfEntries)) \{ // Assertion: The list is not
empty Node desiredNode = getNodeAt (givenPosition); ToriginalEntry = desiredNode.getData();
desiredNode.setData(newEntry); return originalEntry; f // end if else throw new
IndexOut0fBoundsException("Illegal position given to replace operation."); replace if ((
givenPosition >=1)&& (givenPosition <= number0fEntries)) \{ // Assertion: The list is not
empty Node desiredNode = getNodeAt ( givenPosition); T originalEntry = desiredNode.
getData( ); desiredNode.setData(newEntry); return originalentry; \} // end if throw new
Index0ut0fBoundsException("Illegal position given to replace operation."); \} // end replace
public T getEntry(int givenPosition) \{ if ((givenPosition >=1) \&\& (givenPosition < =
number0fEntries ) ) \{ // Assertion: The list is not empty return getNodeAt (givenPosition).
getData(); else // end if throw new IndexOut0fBoundsException("Illegal position given to
getEntry operation."); \} // end getEntry public boolean contains ( T anEntry) \{ boolean found =
false; Node currentNode = firstNode; while (!found && (currentNode != null)) \{ if
(anEntry.equals (currentNode.getData())) else found = true; \} // end while currentNode =
currentNode. getNextNode () ; return found; \} // end contains public int getLength() \{ return
numberofEntries; \} // end getLength public boolean isEmpty() \{ return number0fEntries ==0;
\} // end isEmpty public T[] toArray() \{ // The cast is safe because the new array contains null
entries aSuppressWarnings ("unchecked") T[] result =(T[]) new 0bject [numberofEntries]; //
Unchecked cast int index =0; Node currentNode = firstNode; while ((index < numberOfEntries)
\&\& (currentNode != null)) \& result [ index ]= currentNode. getData () ; currentNode =
currentNode.getNextNode ( ); index++; 3 // end while return result; 3 // end toArray // Returns a
reference to the node at a given position. // Precondition: L.
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.
I need help implementing a Stack with this java programming assignme.pdfsauravmanwanicp
I need help implementing a Stack with this java programming assignment:
Given a doubly linked list (code provided below) implement a Stack. You must use the doubly
link list class and utilize it as an object in your implementation of the stack.
A Stack is a Last in First Out (LiFO) structure which translates to the processes of outputting the
last element which was inputted in the collection. The Stack is based on the process of putting
things on top of one another and taking the item on top (think of a stack of papers).
Operations to implement:
push (E): Add an element to the start of the sequence
pop: Remove an element from the start of the sequence
Peek: Return the first element of the sequence without removing it
atIndex(x): Return the element at the given index (x) Or throw an exception if it is out of bound
(if you can control the user input then do that instead)
Size: Return the size of the Stack
isEmpty: Boolean, returns true if the Stack is empty
Empty: Empty the Stack
Code Part 1:
public class DoublyLinkedList{
private DNode head;
private DNode tail;
private int size;
public DoublyLinkedList(){ // construct an empty list
this.tail = new DNode (null, null, this.head);
this.head = new DNode (null, this.tail, null);
this.size = 0;
}
public DoublyLinkedList(DNode next){ // constructs a list
// out of a single node
this.tail = new DNode (null, null, next);
this.head = new DNode (null, next, null);
next.changeNext(this.tail);
next.changePrev(this.head);
this.size = 1;
}
public DoublyLinkedList(Object [] objectArray){ // construct a list out of
// an array
this.tail = new DNode (null, null, this.head);
this.head = new DNode (null, this.tail, null);
DNode temp = this.head;
for (Object e : objectArray)
{
//Anonomus function
new DNode (e, temp.getNext(),temp).insertBetweenNodes(temp, temp.getNext());
temp = temp.getNext();
this.size += 1;
}
}
public void addToFrontofList(Object toAdd){ // Appends the begining
// of the list
DNode temp = new DNode (toAdd, this.head.getNext(), this.head);
this.head.getNext().changePrev(temp);
this.head.changeNext(temp);
this.size += 1;
}
public void addToendofList (Object toAdd) // appends the end of the list
// with a node
{
DNode temp = new DNode (toAdd, this.tail, this.tail.getPrev());
this.tail.getPrev().changeNext(temp);
this.tail.changePrev(temp);
this.size += 1;
}
public void insertAfterNode(DNode current, Object input)// Inserts a new
// a new node after
// current node
{
current.insertAfterNode(input);
this.size += 1;
}
public int getSize() // returns the size of the list
{
return this.size;
}
public String toString()
{
String result = \"\";
for (DNode temp = this.head.getNext();
temp.hasNext(); temp = temp.getNext())
{
result += temp.getValue();
result += \" -> \";
}
result += \"End of list\";
return result;
}
}
and code part2:
public class DNode{
private Object e; // place holder for the type of object the
//collection is storing
private DNode next; // reference to the next node in the sequence
// of.
This assignment and the next (#5) involve design and development of a.pdfEricvtJFraserr
This assignment and the next (#5) involve design and development of a sequential
non contiguous and dynamic datastructure called LinkedList. A linked list object is
a container consisting of connected ListNode objects. As before, we are not going
to use pre-fabricated classes from the c++ library, but construct the LinkedList
ADT from scratch.
The first step is construction and testing of the ListNode class. A ListNode object
contains a data field and a pointer to the next ListNode object (note the recursive
definition).
#This assignment requires you to
1. Read the Assignment 4 Notes
2. Watch the Assignment 4 Support video
3. Implement the following methods of the ListNode class
-custom constructor
-setters for next pointer and data
4. Implement the insert and remove method in the main program
5. Scan the given template to find the above //TODO and implement the code
needed
//TODO in ListNodecpp.h file
public: ListNode(T idata, ListNode<T> * newNext);
public: void setNext(ListNode<T> * newNext);
public: void setData(T newData);
// TODO in main program
void remove(ListNode<int> * &front,int value)
void insert(ListNode<int> * &front,int value)
# The driver is given ListNodeMain.cpp is given to you that does the following
tests
1. Declares a pointer called front to point to a ListNode of datatype integer
2. Constructs four ListNodes with data 1,2,4 and adds them to form a linked
list.
3. Inserts ListNode with data 3 to the list
4. Removes node 1 and adds it back to test removing and adding the first
element
5. Removes node 3 to test removing a middle node
6. Removes node 4 to test removing the last node
7. Attempt to remove a non existent node
8. Remove all existing nodes to empty the list
9. Insert node 4 and then node 1 to test if insertions preserve order
10.Print the list
Main.cpp
#include <iostream>
#include "ListNodecpp.h"
// REMEMBER each ListNode has two parts : a data field
// and an address field. The address is either null or points to the next node
//in the chain
//Requires: integer value for searching, address of front
//Effects: traverses the list node chain starting from front until the end comparing search value
with listnode getData. Returns the original search value if found, if not adds +1 to indicate not
found
//Modifies: Nothing
int search(ListNode<int> * front, int value);
//Requires: integer value for inserting, address of front
//Effects: creates a new ListNode with value and inserts in proper position (increasing order)in
the chain. If chain is empty, adds to the beginning
//Modifies: front, if node is added at the beginning.
//Also changes the next pointer of the previous node to point to the
//newly inserted list node. the next pointer of the newly inserted pointer
//points to what was the next of the previous node.
//This way both previous and current links are adjusted
//******** NOTE the use of & in passing pointer to front as parameter -
// Why do you think this is needed ?**********
void insert(ListNode<int> * &fr.
How do I fix it in javaLinkedList.java Defines a doubl.pdffmac5
How do I fix it in java?
LinkedList.java:
/**
* Defines a doubly-linked list class
* @author
* @author
*/
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() {
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) {
}
/**** ACCESSORS ****/
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;
}
/**
* Returns the data stored in the iterator node
* @precondition
* @return the data stored in the iterator node
* @throw NullPointerException
*/
public T getIterator() throws NullPointerException {
if (iterator != null){
return iterator.data;
}else{
throw new NullPointerException("Iterator is off the end opf the list.");
}
}
/**
* Returns the current length of the LinkedList
* @return the length of the LinkedList from 0 to n
*/
public int getLength() {
return length;
}
/**
* Returns whether the LinkedList is currently empty
* @return whether the LinkedList is empty
*/
public boolean isEmpty() {
return length == 0;
}
/**
* Returns whether the iterator is offEnd, i.e. null
* @return whether the iterator is null
*/
public boolean offEnd() {
return iterator == null;
}
/**** MUTATORS ****/
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++;
}
/**
* Inserts a new element after the iterator
* @param data the data to insert
* @precondition
* @throws NullPointerException
*/
public void addIterator(T data) throws NullPointerException{
if(iterator != null){
Node newNode = new Node(data);
newNode.next = iterator.next;
iterator.next = newNode;
if (iterator == first){
first = newNode;
}
}else{
throw new NullPointerException("Iterator is off the end opf the list.");
}
}
/
public void removeFirst() throws NoSuchElementException {
if(is.
--INSTRUCTION- --It helps to first create if-then-else structure to fi.pdfAdrianEBJKingr
//INSTRUCTION:
//It helps to first create if-then-else structure to fill in later.
//- Make sure PURPOSE and PARAMETER comments are given in detail
// Add sufficient comments to your code body to describe what it does.
// - Make sure all if-then-else are commented describing which case it is
// - Make sure all local variables are described fully with their purposes
//Complete the TODO parts.
// ====================================================
//Complier: g++
//File type: linkedList.cpp implementation file
//=====================================================
#include<iostream>
#include"linkedlist.h"
using namespace std;
//cunstructor that initializes an empty list
LinkedList::LinkedList() {
front = nullptr ;
rear = nullptr ;
count = 0;
}
/**
* @brief Destructor to destroy all nodes and release memory
*/
LinkedList::~LinkedList() {
Node *p, *q;
p = front;
while (p != nullptr ) {
q = p->next;
delete p;
p = q;
}
}
/**
* @brief Purpose: Checks if the list is empty
* @return true if the list is empty, false otherwise
*/
bool LinkedList::isEmpty() const {
// TODO: Add code here
return count == 0;
}
/**
* @brief Get the number of nodes in the list
* @return int The number of nodes in the list
*/
int LinkedList::length() const {
return count;
}
/**
* @brief Convert the list to a string
*
*/
string LinkedList::toString() {
string str = "[";
Node *ptr = front;
if (ptr != nullptr ) {
// Head node is not preceded by separator
str += to_string(ptr->val);
ptr = ptr->next;
}
while (ptr != nullptr ) {
str += ", " + to_string(ptr->val);
ptr = ptr->next;
}
str += "]";
return str;
}
/**
* @brief Displays the contents of the list
*/
void LinkedList::displayAll() {
cout << toString() << endl;
}
//Add a node to the end of the list
void LinkedList::addRear(T val) {
Node *p = new Node;
p->val = val;
p->next = nullptr ;
if (isEmpty()) {
front = p;
}
else {
rear->next = p;
}
rear = p;
count++;
// consider the two cases of whether the list was empty
}
//Add a node to the front of the list
void LinkedList::addFront(T val) {
Node *p = new Node;
p->val = val;
p->next = front;
if (isEmpty()) {
rear = p;
}
front = p;
count++;
// consider the two cases of whether the list was empty
}
//Delete the first node of the list
bool LinkedList::deleteFront(T &OldNum) {
if (isEmpty()) {
return false ;
}
Node *p = front;
OldNum = p->val;
front = front->next;
if (front == nullptr ) {
rear = nullptr ;
}
delete p;
count--;
return true ;
// consider if the list was empty and return false if the list is empty
// consider the special case of deleting the only node in the list
}
//Delete the last node of the list
bool LinkedList::deleteRear(T &OldNum) {
if (isEmpty()) {
return false ;
}
Node *p = rear;
OldNum = p->val;
if (front == rear) {
front = rear = nullptr ;
}
else {
Node *q = front;
while (q->next != rear) {
q = q->next;
}
rear = q;
q->next = nullptr ;
}
delete p;
count--;
return true ;
// consider if the list was empty and return false if the list is empty
// consider the specia.
How do I fix it in LinkedList.javaLinkedList.java Define.pdfmail931892
How do I fix it in LinkedList.java?
LinkedList.java:
/**
* Defines a doubly-linked list class
* @author
* @author
*/
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() {
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) {
}
/**** ACCESSORS ****/
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;
}
/**
* Returns the data stored in the iterator node
* @precondition
* @return the data stored in the iterator node
* @throw NullPointerException
*/
public T getIterator() throws NullPointerException {
if (iterator != null){
return iterator.data;
}else{
throw new NullPointerException("Iterator is off the end opf the list.");
}
}
/**
* Returns the current length of the LinkedList
* @return the length of the LinkedList from 0 to n
*/
public int getLength() {
return length;
}
/**
* Returns whether the LinkedList is currently empty
* @return whether the LinkedList is empty
*/
public boolean isEmpty() {
return length == 0;
}
/**
* Returns whether the iterator is offEnd, i.e. null
* @return whether the iterator is null
*/
public boolean offEnd() {
return iterator == null;
}
/**** MUTATORS ****/
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++;
}
/**
* Inserts a new element after the iterator
* @param data the data to insert
* @precondition
* @throws NullPointerException
*/
public void addIterator(T data) throws NullPointerException{
if(iterator != null){
Node newNode = new Node(data);
newNode.next = iterator.next;
iterator.next = newNode;
if (iterator == first){
first = newNode;
}
}else{
throw new NullPointerException("Iterator is off the end opf the list.");
}
}
/
public void removeFirst() throws NoSuchElementExcept.
gen diffuses Oxygen enters a from the blood to red blood cell. the bo.pdfmalavshah9013
gen diffuses Oxygen enters a from the blood to red blood cell. the body\'s tissues oxygen is di
through blood from the alveoli vessels to a into sumounding capillaries. capillary. a molecule of
hemoglobin reset help
Solution
Steps wise -
1.Oxygen is carried through blood vessels to a capillary.
2.Oxygen diffuses from the alveoli into surrounding capillaries.
3.Oxygen enters a red blood cell.
4.Oxygen binds to a molecule of hemoglobin.
5.Oxygen diffuses form the blood to the body\'s tissues..
Fill in parameters Public New Hash table (int initial Capacity, floa.pdfmalavshah9013
Fill in parameters Public New Hash table (int initial Capacity, float load Factor) Constructs a
new, empty hash table with the specified initial capacity and the specified load factor.
Parameters: initial Capacity - the initial capacity of the hash table. load Factor - the load factor of
the hash table. Throws: if the initial capacity is less than zero, or if the load factor is nonpositive.
public New hostable (int initial 1Capac.ity) Constructs a new, empty hash table with the
specified initial capacity and default load factor (0.75). Parameters: initia1Capacity - the initial
capacity of the hash table. Throws: IllegalArqumentException - if the initial capacity is less than
zero. public NewHashtable() Constructs a new, empty hash table with a default initial capacity
(11) and load factor (0.75).
Solution
//NewHashTable.java
import java.util.LinkedList;
@SuppressWarnings({ \"unchecked\", \"unused\", \"rawtypes\", \"hiding\" })
public class NewHashTable {
//private class to hold a key and its value
private class HashEntry{
private K key;
private V value;
public HashEntry(K key, V value){
this.key = key;
this.value = value;
}
public String toString(){
return key+\"=\"+value;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof HashEntry))
return false;
HashEntry other = (HashEntry) obj;
return (key.equals(other.key));
}
}
private int capacity;
private float loadFactor;
private LinkedList[] table;
private int size;
//Default Constructor
public NewHashTable(){
capacity = 11;
loadFactor = .75f;
table =new LinkedList[capacity];
for(LinkedList bucket : table)
bucket = null;
size = 0;
}
//One argument Constructor
//@param initialCapacity initial capacity of table
public NewHashTable(int initialCapacity){
if(initialCapacity<0)
throw new IllegalArgumentException(\"\"+initialCapacity);
capacity = initialCapacity;
loadFactor = .75f;
table = new LinkedList[capacity];
for(LinkedList bucket : table)
bucket = null;
size = 0;
}
//Two argument Constructor
//@param initialCapacity initial capacity of this NewHashTable
//@param loadFactor customized loadFactor
public NewHashTable(int initialCapacity, float loadFactor){
if(initialCapacity<0)
throw new IllegalArgumentException(\"Capacity: \"+initialCapacity);
if(loadFactor<0)
throw new IllegalArgumentException(\"Load Factor: \"+loadFactor);
capacity = initialCapacity;
this.loadFactor = loadFactor;
}
//@return capacity the capacity of this NewHashTable
public int getCapacity(){
return capacity;
}
//@return true if this NewHashTable is empty, false otherwise
public boolean isEmpty(){
return size==0;
}
//@return size the number of keys in this NewHashTable
public int size(){
return size;
}
//@param key key to be searched for in this NewHashTable
//@return true if key is found within this NewHashTable
public boolean containsKey(K key){
int hash = Math.abs(key.hashCode()%capacity);
return table[hash]!=null
&&table[hash].contains(new HashEntry(key,null));
}
//Increases the capacity and reorganizes this Ne.
More Related Content
Similar to The LinkedList1 class implements a Linked list. class.pdf
Data Structures in C++I am really new to C++, so links are really .pdfrohit219406
Data Structures in C++
I am really new to C++, so links are really hard topic for me. It would be nice if you can provide
explanations of what doubly linked lists are and of some of you steps... Thank you
In this assignment, you will implement a doubly-linked list class, together with some list
operations. To make things easier, you’ll implement a list of int, rather than a template class.
Solution
A variable helps us to identify the data. For ex: int a = 5; Here 5 is identified through variable a.
Now, if we have collection of integers, we need some representation to identify them. We call it
array. For ex: int arr[5]
This array is nothing but a Data Structure.
So, a Data Structure is a way to group the data.
There are many Data Structures available like Arrays, Linked List, Doubly-Linked list, Stack,
Queue, etc.
Doubly-Linked list are the ones where you can traverse from the current node both in left and
right directions.
Why so many different types of Data Structures are required ?
Answer is very simple, grouping of data, storage of data and accessing the data is different.
For example, in case of Arrays we store all the data in contiguous locations.
What if we are not able to store the data in contiguous locations because we have huge data.
Answer is go for Linked List/Doubly-Linked list.
Here we can store the data anywhere and link the data through pointers.
I will try to provide comments for the code you have given. May be this can help you.
#pragma once
/*
dlist.h
Doubly-linked lists of ints
*/
#include
class dlist {
public:
dlist() { }
// Here we are creating a NODE, it has a integer value and two pointers.
// One pointer is to move to next node and other to go back to previous node.
struct node {
int value;
node* next;
node* prev;
};
// To return head pointer, i.e. start of the Doubly-Linked list.
node* head() const { return _head; }
// To return Tail pointer, i.e. end of the Doubly-Linked list.
node* tail() const { return _tail; }
// **** Implement ALL the following methods ****
// Returns the node at a particular index (0 is the head).
node* at(int index){
int cnt = 0;
struct node* tmp = head();
while(tmp!=NULL)
{
if (cnt+1 == index)
return tmp;
tmp = tmp->next;
}
}
// Insert a new value, after an existing one
void insert(node *previous, int value){
// check if the given previous is NULL
if (previous == NULL)
{
printf(\"the given previous node cannot be NULL\");
return;
}
// allocate new node
struct node* new_node =(struct node*) malloc(sizeof(struct node));
// put in the data
new_node->data = new_data;
// Make next of new node as next of previous
new_node->next = previous->next;
// Make the next of previous as new_node
previous->next = new_node;
// Make previous as previous of new_node
new_node->prev = previous;
// Change previous of new_node\'s next node
if (new_node->next != NULL)
new_node->next->prev = new_node;
}
// Delete the given node
void del(node* which){
struct node* head_ref = head();
/* base case */
if(*head_ref == NUL.
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.
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 =.
public class MyLinkedListltE extends ComparableltEgtg.pdfaccostinternational
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++; // Increase size
}
public void add(int index, E e) {
if (index == 0) {
addFirst(e);
}
else if (index >= size) {
addLast(e);
}
else {
Node<E> current = head;
for (int i = 1; i < index; i++) {
current = current.next;
}
Node<E> temp = current.next;
current.next = new Node<>(e);
(current.next).next = temp;
size++;
}
}
//Add e to the end of this linkedlist
public void add(E e) {
// Left as Exercise
}
/** Remove the head node and
* return the object that is contained in the removed node. */
public E removeFirst() {
if (size == 0) {
return null;
}
else {
E temp = head.element;
head = head.next;
size--;
if (head == null) {
tail = null;
}
return temp;
}
}
/** Remove the last node and
* return the object that is contained in the removed node. */
public E removeLast() {
if (size == 0) {
return null;
}
else if (size == 1) {
E temp = head.element;
head = tail = null;
size = 0;
return temp;
}
else {
Node<E> current = head;
for (int i = 0; i < size - 2; i++) {
current = current.next;
}
E temp = tail.element;
tail = current;
tail.next = null;
size--;
return temp;
}
}
/** Remove the element at the specified position in this
* list. Return the element that was removed from the list. */
public E remove(int index) {
if (index < 0 || index >= size) {
return null;
}
else if (index == 0) {
return removeFirst();
}
else if (index == size - 1) {
return removeLast();
}
else {
Node<E> previous = head;
for (int i = 1; i < index; i++) {
previous = previous.next;
}
Node<E> current = previous.next;
previous.next = current.next;
size--;
return current.element;
}
}
/** Clear the list */
public void clear() {
size = 0;
head = tail = null;
}
/** Override toString() to return elements in the list in [] separated by , */
public String toString() {
StringBuilder result = new StringBuilder("[");
Node<E> current = head;
for (int i = 0; i < size; i++) {
result.append(current..
Class DiagramIn the Assignment #10, you are given three files Ass.pdfxlynettalampleyxc
Class Diagram:
In the Assignment #10, you are given three files Assignment10.java, LinkedList.java, and
ListIterator.java. You will need to add additional methods in the LinkedList class in the
LinkedList.java file. The LinkedList will be tested using strings only.
Specifically, the following methods must be implemented in the LinkedList class:
(You should utilize listIterator() method already defined in the LinkedList class to obtain its
LinkedListIterator object, and use the methods in the LinkedListIterator class to traverse from
the first element to the last element of the linked list to define the following methods.)
1.
public String toString()
The toString method should concatenate strings in the linked list, and return a string of the
following format:
{ Apple Banana Melon Orange }
Thus it starts with \"{\" and ends with \"}\", and there is a space between strings and \"{\" or
\"}\". If the list is empty, it returns \"{ }\" with a space in between.
2.
public boolean isEmpty()
The isEmpty method returns true of the linked list is empty, false otherwise.
3.
public void addElement(Object element)
The addElement adds the parameter element at the parameter in the linked list in alphabetical
order. For instance, if the linked list contains {Apple, Banana, Grape}, and a user tries to add
\"Carrot\", then it should be added as:
{Apple, Banana, Carrot, Grape}.
4.
public Object removeElement(int index)
The removeElement removes the string (Object) at the parameter index and returns it. Note that
this index starts with 0 just like array indices. For instance, if the linked list contains {Apple,
Banana, Carrot, Grape} and the parameter index is 3, then \"Grape\" should be remove. If the
parameter index is larger or smaller than the existing indices, it should throw an object of the
IndexOutOfBoundsException class (and the content of the linked list should remain unchanged).
5.
public Object getElement(int index)
The getElement searches the string (Object) at the parameter index and returns it. Note that this
index starts with 0 just like array indices. For instance, if the linked list contains {Apple, Banana,
Carrot, Grape} and the parameter index is 3, then \"Grape\" will be returned. If the parameter
index is larger or smaller than the existing indices, it should throw an object of the
IndexOutOfBoundsException class (and the content of the linked list should remain unchanged).
6.
public void searchAndReplace(Object oldString, Object newString)
The searchAndReplace method searches all occurrences of the first parameter string (object) in
the list, and replaces them with the second parameter string (object). If the parameter string does
not exist in the linked list, then the linked list content will not change.
7.
public int indexOfLast(Object searchString)
The indexOfLast searches the parameter string (object) with the largest index, and returns its
index. If the parameter string does not exist in the linked list, then it should return -1.
For i.
Please complete all the code as per instructions in Java programming.docxcgraciela1
Please complete all the code as per instructions in Java programming import org.w3c.dom.Node; import javax.xml.crypto.NodeSetData; import java.awt.*; import java.util.Iterator; import java.util.NoSuchElementException; /** * This class implements an acyclic (non-cyclic), doubly-linked list. * @param */ public class CiscDoublyLinkedList implements CiscList { /** * A reference to the first node in the list (or null if list is empty). */ private Node head; /** * A reference to the last node int the list (or null if list is empty). */ private Node tail; /** * Number of elements in the list. */ private int size; /** * Returns the number of elements in this list. * * * @return the number of elements in this list */ @Override public int size() { return size; } /** * Returns {@code true} if this list contains no elements. * * * @return {@code true} if this list contains no elements */ @Override public boolean isEmpty() { if (size == 0){ return true; } return false; } /** * Returns {@code true} if this list contains the specified element (compared using the {@code equals} method). * * * @param o element whose presence in this list is to be tested * @return {@code true} if this list contains the specified element * @throws NullPointerException if the specified element is null */ @Override public boolean contains(Object o) { if(o == null) { throw new NullPointerException(); } Node node = head; while(node != null) { if(node.data.equals(o)){ return true; } node = node.next; } return false; } /** * Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not * contain the element (compared using the {@code equals} method). * * * @param o element to search for * @return the index of the first occurrence of the specified element in this list, or -1 if this list does not * contain the element * @throws NullPointerException if the specified element is null */ @Override public int indexOf(Object o) { if (o == null){ throw new NullPointerException(); } for(int i =0; i = size){ throw new IndexOutOfBoundsException(); } return null; } /** * Appends the specified element to the end of this list. * * *
Lists may place the specified element at arbitrary locations if desired. In particular, an ordered list will * insert the specified element at its sorted location. List classes should clearly specify in their documentation * how elements will be added to the list if different from the default behavior (end of this list). * * @param e element to be appended to this list * @return {@code true} * @throws NullPointerException if the specified element is null */ @Override public boolean add(E e) { if(e == null){ throw new NullPointerException(); } return false; } /** * Replaces the element at the specified position in this list with the specified element. * * * @param index index of the element to replace * @param element element to be stored at the specified position * @return the element previously at the specified position *.
LabProgram.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 ****/
/**
* Instantiates a new LinkedList with default values
* @postcondition
*/
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) {
}
/**** ACCESSORS ****/
/**
* Returns the value stored in the first node
* @precondition <>
* @return the value stored at node first
* @throws NoSuchElementException <>
*/
public T getFirst() throws NoSuchElementException {
if (isEmpty()){
throw new NoSuchElementException("The list is empty");
}
return first.data;
}
/**
* Returns the value stored in the last node
* @precondition <>
* @return the value stored in the node last
* @throws NoSuchElementException <>
*/
public T getLast() throws NoSuchElementException {
if (isEmpty()){
throw new NoSuchElementException("The list is empty");
}
return last.data;
}
/**
* 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 iterator.data;
}
/**
* Returns the current length of the LinkedList
* @return the length of the LinkedList from 0 to n
*/
public int getLength() {
return length;
}
/**
* Returns whether the LinkedList is currently empty
* @return whether the LinkedList is empty
*/
public boolean isEmpty() {
return length == 0;
}
/**
* Returns whether the iterator is offEnd, i.e. null
* @return whether the iterator is null
*/
public boolean offEnd() {
return iterator == null;
}
/**** MUTATORS ****/
/**
* Creates a new first element
* @param data the data to insert at the front of the LinkedList
* @postcondition <>
*/
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++;
}
/**
* Creates a new last element
* @param data the data to insert at the end of the LinkedList
* @postcondition <>
*/
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++;
}
/**
* Inserts a new element after the iterator
* @param data the data to insert
* @precondition
* @throws NullPointerException
*/
public void addIter.
Consider a double-linked linked list implementation with the followin.pdfsales98
Consider a double-linked linked list implementation with the following node: struct Node {int
data; Node *prev; Node *next;} Write a copyList method that is not a member of any class.
The method should take a head pointer and return another pointer. Do not modify the input.
Solution
struct Node {
Node *prev; // previous node
Node *next; // next node
int data; // stored value
};
#include
#include \"List.h\" // std: #include
using namespace std;
typedef DataList ; // std: typedef list Data;
int main() {
Data k;
// back stuff
k.push_back(5);
k.push_back(6);
cout << k.back() << endl;
k.pop_back();
// front stuff
k.push_front(4);
k.push_front(3);
cout << k.front() << endl;
k.pop_front();
// forward iterator
Data::iterator pos;
for (pos = k.begin(); pos != k.end(); ++pos)
cout << *pos << endl;
// output and delete list
while (!k.empty()) {
cout << k.front() << endl;
k.pop_front();
}
k.push_front(5);
k.push_front(6);
// remove and erase
k.remove(5);
pos = k.begin();
k.erase(pos);
k.push_front(5);
k.push_front(6);
// copy constructor
Data l = k;
// assignment operator
Data m;
m = k;
return 0;
}
// List.h
struct Node;
classIterator List;
class List {
public:
typedef ListIterator iterator;
// constructor
List();
// destructor
virtual ~List();
// copy constructor
List(const List& k);
// assignment operator
List& operator=(const List& k);
// insert value in front of list
void push_front(double data);
// insert value in back of list
void push_back(double data);
// delete value from front of list
void pop_front();
// delete value from back of list
void pop_back();
// return value on front of list
double front() const;
// return value on back of list
double back() const;
// delete value specified by iterator
void erase(const iterator& i);
// delete all nodes with specified value
void remove(double data);
// return true if list is empty
bool empty() const;
// return reference to first element in list
iterator begin() const;
// return reference to one past last element in list
iterator end() const;
private:
Node *head; // head of list
};
class ListIterator {
public:
// default constructor
ListIterator() {
i = 0;
}
// construct iterator for given pointer (used for begin/end)
ListIterator(Node *p) {
i = p;
}
// convert iterator to Node*
operator Node*() const {
return i;
}
// test two iterators for not equal
bool operator!=(const ListIterator& k) const {
return i != k.i;
}
// preincrement operator
ListIterator& operator++() {
i = i->next;
return *this;
}
// return value associated with iterator
double& operator*() const {
return i->data;
}
private:
Node *i; // current value of iterator
};
list.cpp
// delete list
static void deleteList(Node *head) {
Node *p = head->next;
while (p != head) {
Node *next = p->next;
delete p;
p = next;
}
delete head;
}
// copy list
static void copyList(const Node *from, Node *&to) {
// create dummy header
to = new Node;
to->next = to->prev = to;
// copy nodes
for (Node *p = from->next; p != from; p = p->next) {
Node *t = new Node;
t.
Design, implement, test(In Java ) a doubly linked list ADT, using DL.pdftrishacolsyn25353
Design, implement, test(In Java ) a doubly linked list ADT, using DLLNode objects as the
nodes. In addition to our standard list operations, your class should provide for backward
iteration through the list. To support this operation, it should export a resetBack method and get a
getPrevious method.To facilitate this, you may want to include an instance variable last that
always references the last element on the list.
DLLNODE.java
public class DLLNode extends LLNode
{
private DLLNode back;
public DLLNode(T info)
{
super(info);
back = null;
}
public void setBack(DLLNode back)
// Sets back link of this DLLNode.
{
this.back = back;
}
public DLLNode getBack()
// Returns back link of this DLLNode.
{
return back;
}
}
LLNODE.java
public class LLNode
{
private LLNode link;
private T info;
public LLNode(T info)
{
this.info = info;
link = null;
}
public void setInfo(T info)
// Sets info of this LLNode.
{
this.info = info;
}
public T getInfo()
// Returns info of this LLONode.
{
return info;
}
public void setLink(LLNode link)
// Sets link of this LLNode.
{
this.link = link;
}
public LLNode getLink()
// Returns link of this LLNode.
{
return link;
}
}
This list can be an unsorted list. My professor suggested to reference off the RefUnsortedList
ADT and modifying it to be a doubly linked list.you need to create resetBack and getPrevious
methods which means you will need another variable to keep track of where you are in the
backward iteration. It is not correct to use currentPos to keep track of the backward iteration, so
make another variable (reference) for this, maybe call it currentBackPos.
RefUnsortedList.java
public class RefUnsortedList implements ListInterface
{
protected int numElements; // number of elements in this list
protected LLNode currentPos; // current position for iteration
// set by find method
protected boolean found; // true if element found, else false
protected LLNode location; // node containing element, if found
protected LLNode previous; // node preceeding location
protected LLNode list; // first node on the list
public RefUnsortedList()
{
numElements = 0;
list = null;
currentPos = null;
}
public void add(T element)
// Adds element to this list.
{
LLNode newNode = new LLNode(element);
newNode.setLink(list);
list = newNode;
numElements++;
}
protected void find(T target)
// Searches list for an occurence of an element e such that
// e.equals(target). If successful, sets instance variables
// found to true, location to node containing e, and previous
// to the node that links to location. If not successful, sets
// found to false.
{
location = list;
found = false;
while (location != null)
{
if (location.getInfo().equals(target)) // if they match
{
found = true;
return;
}
else
{
previous = location;
location = location.getLink();
}
}
}
public int size()
// Returns the number of elements on this list.
{
return numElements;
}
public boolean contains (T element)
// Returns true if this list contains an element e such that
// e.equals(el.
To complete the task, you need to fill in the missing code. I’ve inc.pdfezycolours78
To complete the task, you need to fill in the missing code. I’ve included code to create an
Iterator. An Iterator is an object that iterates over another object – in this case, a circular linked
list. You can use the .next() method to advance the Iterator to the next item (the first time you
call it, the iterator will travel to node at index 0). Using iterator’s .remove() removes the node the
iterator is currently at. Say that we had a CircularLinkedList that looked like this: A ==> B ==>
C ==> D ==> E ==> Calling .next() three times will advance the iterator to index 2. Calling
.remove() once will remove the node at index 2. A ==> B ==> D ==> E ==> Calling .remove()
once more will remove the node now at index 2. A ==> B ==> E ==> The Iterator methods
handle wrapping around the CircularLinkedList. Be sure to create the iterator using l.iterator()
and after you’ve added all the nodes to the list, where l is your CircularLinkedList
Solution
import java.util.Iterator;
class CircularLinkedList implements Iterable {
// Your variables
// You can include a reference to a tail if you want
Node head;
int size; // BE SURE TO KEEP TRACK OF THE SIZE
// implement this constructor
public CircularLinkedList() {
head=null;
}
// writing helper functions for add and remove, like the book did can help
// but remember, the last element\'s next node will be the head!
// attach a node to the end of the list
// Be sure to handle the adding to an empty list
// always returns true
public boolean add(E e) {
Node newNode=new Node(e);
if(size==0){
head=newNode;
}
else{
Node last=getNode(size-1);
last.next=newNode;
}
newNode.next=head; //last element node is set to head
size++;
return true;
}
// need to handle
// out of bounds
// empty list
// adding to front
// adding to middle
// adding to \"end\"
// REMEMBER TO INCREMENT THE SIZE
public boolean add(int index, E e){
if(index>size) return false;
Node tmp=new Node(e);
if(index==0){
tmp.next=head;
Node last=getNode(size-1);
head=tmp;
last.next=head;
}
else {
Node curr=getNode(index-1);
tmp.next=curr.next;
curr.next=tmp;
}
size++;
return true;
}
// I highly recommend using this helper method
// Return Node found at the specified index
// be sure to handle out of bounds cases
private Node getNode(int index ) {
Node prev=head;
for(int i=0;isize) {
e=null;
}
else if(index==0){
e = head.getElement();
Node last=getNode(size-1);
head=head.next;
last.next=head;
size--;
}
else{
Node prev=getNode(index-1);
Node curr=getNode(index);
e=curr.getElement();
prev.next=curr.next;
size--;
}
return e;
}
// Turns your list into a string
// Useful for debugging
public String toString(){
Node current = head;
StringBuilder result = new StringBuilder();
if(size == 0){
return \"\";
}
if(size == 1) {
return head.getElement().toString();
}
else{
do{
result.append(current.getElement());
result.append(\" ==> \");
current = current.next;
} while(current != head);
}
return result.toString();
}
public Iterator iterator() {
return new ListIterator();
}
/.
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.
Homework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdfezzi97
Homework 05 - Linked Lists (C++)
(1) Implement the concepts of a union, and difference as defined noted in Chapter 1 questions 6,
and 8 using a linked list. You should not use arrays, dynamic arrays or the STL vector or STL
list classes.
You will be linking a series of nodes together to implement a single linked list class. Define a
Node as a struct that holds a character (like they did in the book) and a pointer to another Node:
struct Node {
char data;
Node* next;
};
Then define a LinkedList class which has (at a minimum) these member functions:
LinkedList();
~LinkedList();
bool insertAtFront();
bool insertBeforePosition(int index);
bool insertAtBack();
bool deleteAtFront();
bool deleteBeforePosition(int index);
bool deleteAtBack();
Implement each of these functions to provide the correct functionality. These functions return
true if successful in inserting or deleting, otherwise they return false (indicating the operation
was not successful).
Finally, create an overloaded + operator to handle the Union of two linked lists and an
overloaded - operator to handle the Difference of two linked lists.
Because we are dealing with pointers you should have both a LinkedList Constructor and
Destructor. Remember that you do not directly call a Constructor or Destructor Function. The
Destructor is automatically called when the variable loses scope or the program ends.
Remember, that we are dealing with not just one dynamically allocated Node (with the new
operator), but many, so you will have to start at the head of the list and go until the Node points
to nullptr. Then keep deleting the previous Node pointer until there are no Nodes left to delete.
(2) To verify your set class, write a main function that takes two lines of characters from the
input file input.txt and store each line of characters into two separate linked lists. Then using
these two lists, perform the Union and set Difference of the characters from the file, and print the
results to the console.
(3) Please also complete an asymptotic (Big O) analysis of your insertAtFront() and
insertAtBack() member functions. Place this in a file called analysis.txt.
Solution
Here is the complete code for your question. Please do rate the aswer if you are happy with
program. Please read comments in the program. Also pay special attention to comments in + and
- operators. You WILL NEED to comment out if condition in + if you want all elements in both
lists irrespective of if they duplicates or no. For now implemented to have true behaviour of no
duplicates in union.
check the functions by creating some lists and playing around different fucntions like its done in
main and commented out.
As far as complexity:
for insertAtFront() its O(1) since it does not depend on the size of the list. It just replaces the start
of the list. Hence it is O(1) and independent of the size of list.
for insertAtBack(), its O(n) since it depends on the number of elements in the list. It should
traverse till end of list and .
Dividing a linked list into two sublists of almost equal sizesa. A.pdftesmondday29076
Dividing a linked list into two sublists of almost equal sizes
a. Add the operation divideMid to the class linkedListType as follows:
Consider the following statements:
unorderedLinkedList myList;
unorderedLinkedList subList;
Suppose myList points to the list with elements 34 65 27 89 12 (in this order). The statement:
myList.divideMid(subList); divides myList into two sublists: myList points to the list with the
elements 34 65 27,
and subList points to the sublist with the elements 89 12.
b. Write the definition of the function template to implement the operation divideMid. Also,
write a program to test your function. The header files linkedList.h and unorderedLinkedList.h
are supplied. Your test program should produce output similar to this:
Turn in:
linkedList.h with modifications
Your test program.
(C++)
Required code is below:
#ifndef H_UnorderedLinkedList
#define H_UnorderedLinkedList
#include \"linkedList.h\"
using namespace std;
template
class unorderedLinkedList: public linkedListType
{
public:
bool search(const Type& searchItem) const;
//Function to determine whether searchItem is in the list.
//Postcondition: Returns true if searchItem is in the
// list, otherwise the value false is
// returned.
void insertFirst(const Type& newItem);
//Function to insert newItem at the beginning of the list.
//Postcondition: first points to the new list, newItem is
// inserted at the beginning of the list,
// last points to the last node in the
// list, and count is incremented by 1.
void insertLast(const Type& newItem);
//Function to insert newItem at the end of the list.
//Postcondition: first points to the new list, newItem
// is inserted at the end of the list,
// last points to the last node in the
// list, and count is incremented by 1.
void deleteNode(const Type& deleteItem);
//Function to delete deleteItem from the list.
//Postcondition: If found, the node containing
// deleteItem is deleted from the list.
// first points to the first node, last
// points to the last node of the updated
// list, and count is decremented by 1.
};
template
bool unorderedLinkedList::
search(const Type& searchItem) const
{
nodeType *current; //pointer to traverse the list
bool found = false;
current = this->first; //set current to point to the first
//node in the list
while (current != NULL && !found) //search the list
if (current->info == searchItem) //searchItem is found
found = true;
else
current = current->link; //make current point to
//the next node
return found;
}//end search
template
void unorderedLinkedList::insertFirst(const Type& newItem)
{
nodeType *newNode; //pointer to create the new node
newNode = new nodeType; //create the new node
newNode->info = newItem; //store the new item in the node
newNode->link = this->first; //insert newNode before first
this->first = newNode; //make first point to the
//actual first node
this->count++; //increment count
if (this->last == NULL) //if the list was empty, newNode is also
//the last node in the list
this->l.
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdfclimatecontrolsv
PROBLEM STATEMENT:
In this assignment, you will complete DoubleEndedList.java that implements the ListInterface as
well as an interface called DoubleEndedInterface which represents the list's entries by using a
chain of nodes that has both a head reference and a tail reference. Be sure to read through the
code and understand the implementation.
WHAT IS PROVIDED:
- A driver class to test your code. You should not modify this file!
- A list interface (ListInterface.java)
- A double ended interface (DoubleEndedInterface.java)
- An incomplete DoubleEndedList class (DoubleEndedList.java)
WHAT YOU NEED TO DO:
4. Complete the DoubleEndedList class
4. Run the driver and make sure your output is exactly the same as mine (at the bottom of
Driver.java)
\} // end else numberofEntries--; else throw new IndexOut0fBoundsException("Illegal position
given to remove operation."); return result; // Return removed entry }//endreturnreve public T
replace(int givenPosition, T newEntry) \{ T replace(int givenPosition, T newEntry) \{ if
((givenPosition >=1)&& (givenPosition <= numberOfEntries)) \{ // Assertion: The list is not
empty Node desiredNode = getNodeAt (givenPosition); ToriginalEntry = desiredNode.getData();
desiredNode.setData(newEntry); return originalEntry; f // end if else throw new
IndexOut0fBoundsException("Illegal position given to replace operation."); replace if ((
givenPosition >=1)&& (givenPosition <= number0fEntries)) \{ // Assertion: The list is not
empty Node desiredNode = getNodeAt ( givenPosition); T originalEntry = desiredNode.
getData( ); desiredNode.setData(newEntry); return originalentry; \} // end if throw new
Index0ut0fBoundsException("Illegal position given to replace operation."); \} // end replace
public T getEntry(int givenPosition) \{ if ((givenPosition >=1) \&\& (givenPosition < =
number0fEntries ) ) \{ // Assertion: The list is not empty return getNodeAt (givenPosition).
getData(); else // end if throw new IndexOut0fBoundsException("Illegal position given to
getEntry operation."); \} // end getEntry public boolean contains ( T anEntry) \{ boolean found =
false; Node currentNode = firstNode; while (!found && (currentNode != null)) \{ if
(anEntry.equals (currentNode.getData())) else found = true; \} // end while currentNode =
currentNode. getNextNode () ; return found; \} // end contains public int getLength() \{ return
numberofEntries; \} // end getLength public boolean isEmpty() \{ return number0fEntries ==0;
\} // end isEmpty public T[] toArray() \{ // The cast is safe because the new array contains null
entries aSuppressWarnings ("unchecked") T[] result =(T[]) new 0bject [numberofEntries]; //
Unchecked cast int index =0; Node currentNode = firstNode; while ((index < numberOfEntries)
\&\& (currentNode != null)) \& result [ index ]= currentNode. getData () ; currentNode =
currentNode.getNextNode ( ); index++; 3 // end while return result; 3 // end toArray // Returns a
reference to the node at a given position. // Precondition: L.
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.
I need help implementing a Stack with this java programming assignme.pdfsauravmanwanicp
I need help implementing a Stack with this java programming assignment:
Given a doubly linked list (code provided below) implement a Stack. You must use the doubly
link list class and utilize it as an object in your implementation of the stack.
A Stack is a Last in First Out (LiFO) structure which translates to the processes of outputting the
last element which was inputted in the collection. The Stack is based on the process of putting
things on top of one another and taking the item on top (think of a stack of papers).
Operations to implement:
push (E): Add an element to the start of the sequence
pop: Remove an element from the start of the sequence
Peek: Return the first element of the sequence without removing it
atIndex(x): Return the element at the given index (x) Or throw an exception if it is out of bound
(if you can control the user input then do that instead)
Size: Return the size of the Stack
isEmpty: Boolean, returns true if the Stack is empty
Empty: Empty the Stack
Code Part 1:
public class DoublyLinkedList{
private DNode head;
private DNode tail;
private int size;
public DoublyLinkedList(){ // construct an empty list
this.tail = new DNode (null, null, this.head);
this.head = new DNode (null, this.tail, null);
this.size = 0;
}
public DoublyLinkedList(DNode next){ // constructs a list
// out of a single node
this.tail = new DNode (null, null, next);
this.head = new DNode (null, next, null);
next.changeNext(this.tail);
next.changePrev(this.head);
this.size = 1;
}
public DoublyLinkedList(Object [] objectArray){ // construct a list out of
// an array
this.tail = new DNode (null, null, this.head);
this.head = new DNode (null, this.tail, null);
DNode temp = this.head;
for (Object e : objectArray)
{
//Anonomus function
new DNode (e, temp.getNext(),temp).insertBetweenNodes(temp, temp.getNext());
temp = temp.getNext();
this.size += 1;
}
}
public void addToFrontofList(Object toAdd){ // Appends the begining
// of the list
DNode temp = new DNode (toAdd, this.head.getNext(), this.head);
this.head.getNext().changePrev(temp);
this.head.changeNext(temp);
this.size += 1;
}
public void addToendofList (Object toAdd) // appends the end of the list
// with a node
{
DNode temp = new DNode (toAdd, this.tail, this.tail.getPrev());
this.tail.getPrev().changeNext(temp);
this.tail.changePrev(temp);
this.size += 1;
}
public void insertAfterNode(DNode current, Object input)// Inserts a new
// a new node after
// current node
{
current.insertAfterNode(input);
this.size += 1;
}
public int getSize() // returns the size of the list
{
return this.size;
}
public String toString()
{
String result = \"\";
for (DNode temp = this.head.getNext();
temp.hasNext(); temp = temp.getNext())
{
result += temp.getValue();
result += \" -> \";
}
result += \"End of list\";
return result;
}
}
and code part2:
public class DNode{
private Object e; // place holder for the type of object the
//collection is storing
private DNode next; // reference to the next node in the sequence
// of.
This assignment and the next (#5) involve design and development of a.pdfEricvtJFraserr
This assignment and the next (#5) involve design and development of a sequential
non contiguous and dynamic datastructure called LinkedList. A linked list object is
a container consisting of connected ListNode objects. As before, we are not going
to use pre-fabricated classes from the c++ library, but construct the LinkedList
ADT from scratch.
The first step is construction and testing of the ListNode class. A ListNode object
contains a data field and a pointer to the next ListNode object (note the recursive
definition).
#This assignment requires you to
1. Read the Assignment 4 Notes
2. Watch the Assignment 4 Support video
3. Implement the following methods of the ListNode class
-custom constructor
-setters for next pointer and data
4. Implement the insert and remove method in the main program
5. Scan the given template to find the above //TODO and implement the code
needed
//TODO in ListNodecpp.h file
public: ListNode(T idata, ListNode<T> * newNext);
public: void setNext(ListNode<T> * newNext);
public: void setData(T newData);
// TODO in main program
void remove(ListNode<int> * &front,int value)
void insert(ListNode<int> * &front,int value)
# The driver is given ListNodeMain.cpp is given to you that does the following
tests
1. Declares a pointer called front to point to a ListNode of datatype integer
2. Constructs four ListNodes with data 1,2,4 and adds them to form a linked
list.
3. Inserts ListNode with data 3 to the list
4. Removes node 1 and adds it back to test removing and adding the first
element
5. Removes node 3 to test removing a middle node
6. Removes node 4 to test removing the last node
7. Attempt to remove a non existent node
8. Remove all existing nodes to empty the list
9. Insert node 4 and then node 1 to test if insertions preserve order
10.Print the list
Main.cpp
#include <iostream>
#include "ListNodecpp.h"
// REMEMBER each ListNode has two parts : a data field
// and an address field. The address is either null or points to the next node
//in the chain
//Requires: integer value for searching, address of front
//Effects: traverses the list node chain starting from front until the end comparing search value
with listnode getData. Returns the original search value if found, if not adds +1 to indicate not
found
//Modifies: Nothing
int search(ListNode<int> * front, int value);
//Requires: integer value for inserting, address of front
//Effects: creates a new ListNode with value and inserts in proper position (increasing order)in
the chain. If chain is empty, adds to the beginning
//Modifies: front, if node is added at the beginning.
//Also changes the next pointer of the previous node to point to the
//newly inserted list node. the next pointer of the newly inserted pointer
//points to what was the next of the previous node.
//This way both previous and current links are adjusted
//******** NOTE the use of & in passing pointer to front as parameter -
// Why do you think this is needed ?**********
void insert(ListNode<int> * &fr.
How do I fix it in javaLinkedList.java Defines a doubl.pdffmac5
How do I fix it in java?
LinkedList.java:
/**
* Defines a doubly-linked list class
* @author
* @author
*/
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() {
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) {
}
/**** ACCESSORS ****/
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;
}
/**
* Returns the data stored in the iterator node
* @precondition
* @return the data stored in the iterator node
* @throw NullPointerException
*/
public T getIterator() throws NullPointerException {
if (iterator != null){
return iterator.data;
}else{
throw new NullPointerException("Iterator is off the end opf the list.");
}
}
/**
* Returns the current length of the LinkedList
* @return the length of the LinkedList from 0 to n
*/
public int getLength() {
return length;
}
/**
* Returns whether the LinkedList is currently empty
* @return whether the LinkedList is empty
*/
public boolean isEmpty() {
return length == 0;
}
/**
* Returns whether the iterator is offEnd, i.e. null
* @return whether the iterator is null
*/
public boolean offEnd() {
return iterator == null;
}
/**** MUTATORS ****/
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++;
}
/**
* Inserts a new element after the iterator
* @param data the data to insert
* @precondition
* @throws NullPointerException
*/
public void addIterator(T data) throws NullPointerException{
if(iterator != null){
Node newNode = new Node(data);
newNode.next = iterator.next;
iterator.next = newNode;
if (iterator == first){
first = newNode;
}
}else{
throw new NullPointerException("Iterator is off the end opf the list.");
}
}
/
public void removeFirst() throws NoSuchElementException {
if(is.
--INSTRUCTION- --It helps to first create if-then-else structure to fi.pdfAdrianEBJKingr
//INSTRUCTION:
//It helps to first create if-then-else structure to fill in later.
//- Make sure PURPOSE and PARAMETER comments are given in detail
// Add sufficient comments to your code body to describe what it does.
// - Make sure all if-then-else are commented describing which case it is
// - Make sure all local variables are described fully with their purposes
//Complete the TODO parts.
// ====================================================
//Complier: g++
//File type: linkedList.cpp implementation file
//=====================================================
#include<iostream>
#include"linkedlist.h"
using namespace std;
//cunstructor that initializes an empty list
LinkedList::LinkedList() {
front = nullptr ;
rear = nullptr ;
count = 0;
}
/**
* @brief Destructor to destroy all nodes and release memory
*/
LinkedList::~LinkedList() {
Node *p, *q;
p = front;
while (p != nullptr ) {
q = p->next;
delete p;
p = q;
}
}
/**
* @brief Purpose: Checks if the list is empty
* @return true if the list is empty, false otherwise
*/
bool LinkedList::isEmpty() const {
// TODO: Add code here
return count == 0;
}
/**
* @brief Get the number of nodes in the list
* @return int The number of nodes in the list
*/
int LinkedList::length() const {
return count;
}
/**
* @brief Convert the list to a string
*
*/
string LinkedList::toString() {
string str = "[";
Node *ptr = front;
if (ptr != nullptr ) {
// Head node is not preceded by separator
str += to_string(ptr->val);
ptr = ptr->next;
}
while (ptr != nullptr ) {
str += ", " + to_string(ptr->val);
ptr = ptr->next;
}
str += "]";
return str;
}
/**
* @brief Displays the contents of the list
*/
void LinkedList::displayAll() {
cout << toString() << endl;
}
//Add a node to the end of the list
void LinkedList::addRear(T val) {
Node *p = new Node;
p->val = val;
p->next = nullptr ;
if (isEmpty()) {
front = p;
}
else {
rear->next = p;
}
rear = p;
count++;
// consider the two cases of whether the list was empty
}
//Add a node to the front of the list
void LinkedList::addFront(T val) {
Node *p = new Node;
p->val = val;
p->next = front;
if (isEmpty()) {
rear = p;
}
front = p;
count++;
// consider the two cases of whether the list was empty
}
//Delete the first node of the list
bool LinkedList::deleteFront(T &OldNum) {
if (isEmpty()) {
return false ;
}
Node *p = front;
OldNum = p->val;
front = front->next;
if (front == nullptr ) {
rear = nullptr ;
}
delete p;
count--;
return true ;
// consider if the list was empty and return false if the list is empty
// consider the special case of deleting the only node in the list
}
//Delete the last node of the list
bool LinkedList::deleteRear(T &OldNum) {
if (isEmpty()) {
return false ;
}
Node *p = rear;
OldNum = p->val;
if (front == rear) {
front = rear = nullptr ;
}
else {
Node *q = front;
while (q->next != rear) {
q = q->next;
}
rear = q;
q->next = nullptr ;
}
delete p;
count--;
return true ;
// consider if the list was empty and return false if the list is empty
// consider the specia.
How do I fix it in LinkedList.javaLinkedList.java Define.pdfmail931892
How do I fix it in LinkedList.java?
LinkedList.java:
/**
* Defines a doubly-linked list class
* @author
* @author
*/
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() {
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) {
}
/**** ACCESSORS ****/
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;
}
/**
* Returns the data stored in the iterator node
* @precondition
* @return the data stored in the iterator node
* @throw NullPointerException
*/
public T getIterator() throws NullPointerException {
if (iterator != null){
return iterator.data;
}else{
throw new NullPointerException("Iterator is off the end opf the list.");
}
}
/**
* Returns the current length of the LinkedList
* @return the length of the LinkedList from 0 to n
*/
public int getLength() {
return length;
}
/**
* Returns whether the LinkedList is currently empty
* @return whether the LinkedList is empty
*/
public boolean isEmpty() {
return length == 0;
}
/**
* Returns whether the iterator is offEnd, i.e. null
* @return whether the iterator is null
*/
public boolean offEnd() {
return iterator == null;
}
/**** MUTATORS ****/
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++;
}
/**
* Inserts a new element after the iterator
* @param data the data to insert
* @precondition
* @throws NullPointerException
*/
public void addIterator(T data) throws NullPointerException{
if(iterator != null){
Node newNode = new Node(data);
newNode.next = iterator.next;
iterator.next = newNode;
if (iterator == first){
first = newNode;
}
}else{
throw new NullPointerException("Iterator is off the end opf the list.");
}
}
/
public void removeFirst() throws NoSuchElementExcept.
Similar to The LinkedList1 class implements a Linked list. class.pdf (20)
gen diffuses Oxygen enters a from the blood to red blood cell. the bo.pdfmalavshah9013
gen diffuses Oxygen enters a from the blood to red blood cell. the body\'s tissues oxygen is di
through blood from the alveoli vessels to a into sumounding capillaries. capillary. a molecule of
hemoglobin reset help
Solution
Steps wise -
1.Oxygen is carried through blood vessels to a capillary.
2.Oxygen diffuses from the alveoli into surrounding capillaries.
3.Oxygen enters a red blood cell.
4.Oxygen binds to a molecule of hemoglobin.
5.Oxygen diffuses form the blood to the body\'s tissues..
Fill in parameters Public New Hash table (int initial Capacity, floa.pdfmalavshah9013
Fill in parameters Public New Hash table (int initial Capacity, float load Factor) Constructs a
new, empty hash table with the specified initial capacity and the specified load factor.
Parameters: initial Capacity - the initial capacity of the hash table. load Factor - the load factor of
the hash table. Throws: if the initial capacity is less than zero, or if the load factor is nonpositive.
public New hostable (int initial 1Capac.ity) Constructs a new, empty hash table with the
specified initial capacity and default load factor (0.75). Parameters: initia1Capacity - the initial
capacity of the hash table. Throws: IllegalArqumentException - if the initial capacity is less than
zero. public NewHashtable() Constructs a new, empty hash table with a default initial capacity
(11) and load factor (0.75).
Solution
//NewHashTable.java
import java.util.LinkedList;
@SuppressWarnings({ \"unchecked\", \"unused\", \"rawtypes\", \"hiding\" })
public class NewHashTable {
//private class to hold a key and its value
private class HashEntry{
private K key;
private V value;
public HashEntry(K key, V value){
this.key = key;
this.value = value;
}
public String toString(){
return key+\"=\"+value;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof HashEntry))
return false;
HashEntry other = (HashEntry) obj;
return (key.equals(other.key));
}
}
private int capacity;
private float loadFactor;
private LinkedList[] table;
private int size;
//Default Constructor
public NewHashTable(){
capacity = 11;
loadFactor = .75f;
table =new LinkedList[capacity];
for(LinkedList bucket : table)
bucket = null;
size = 0;
}
//One argument Constructor
//@param initialCapacity initial capacity of table
public NewHashTable(int initialCapacity){
if(initialCapacity<0)
throw new IllegalArgumentException(\"\"+initialCapacity);
capacity = initialCapacity;
loadFactor = .75f;
table = new LinkedList[capacity];
for(LinkedList bucket : table)
bucket = null;
size = 0;
}
//Two argument Constructor
//@param initialCapacity initial capacity of this NewHashTable
//@param loadFactor customized loadFactor
public NewHashTable(int initialCapacity, float loadFactor){
if(initialCapacity<0)
throw new IllegalArgumentException(\"Capacity: \"+initialCapacity);
if(loadFactor<0)
throw new IllegalArgumentException(\"Load Factor: \"+loadFactor);
capacity = initialCapacity;
this.loadFactor = loadFactor;
}
//@return capacity the capacity of this NewHashTable
public int getCapacity(){
return capacity;
}
//@return true if this NewHashTable is empty, false otherwise
public boolean isEmpty(){
return size==0;
}
//@return size the number of keys in this NewHashTable
public int size(){
return size;
}
//@param key key to be searched for in this NewHashTable
//@return true if key is found within this NewHashTable
public boolean containsKey(K key){
int hash = Math.abs(key.hashCode()%capacity);
return table[hash]!=null
&&table[hash].contains(new HashEntry(key,null));
}
//Increases the capacity and reorganizes this Ne.
For Phantom Limb Syndrome, please describe the symptoms and the part .pdfmalavshah9013
For Phantom Limb Syndrome, please describe the symptoms and the part of the brain affected
explicitly, and the cure. How do sea stars\' cat? Describe the Water Vascular System in Sea
Stars (WVS). What is its structure? How does the water get into the WVS? How does it control
the tube feet? Besides moving the tube feet, what does the WVS do?
Solution
1) Phantom limb syndrome is a condition or a sensation in which the cut or missed limb is being
still attached with the person\'s body. It can also be caused due to removal of the body parts due
to the certain reasons.. It affects the brain nerve ending called Neuromas..!!
The symptoms include limb pain in some cases, gesturing, feeling itchiness, and most important
is the feeling of one hand small and long which can bring to severe pain..!!
Some of the cure way of this is meditation, acupuncture, anti-depressants, spinal cord
stimulation..!! Some chemicals like morphine could also be a used...
3) water vascular system is a hydraulic water system present in echinodermata like sea stars.. It
help in food, water movement, locomotion, waste transportation and even respiration too..
They are composed of canals which connects to tube feet . it moves by contacting muscles
present in them which forces the water inside it resulting in extending, pushing on to the ground
and again retracing..
The structure of it is like it has a sieve like structure which is connected to central duct called
amphula. This amphula is connected to another duct called stone canal. This canal runs as a
ambulagrel grooves on each arm of the sea star underside..!! This gives its appearance like a tube
foot.
The contraction of the amphulle cause podia to stretch water inside which allows for the
movement..!!.
Explain why the organisms that were studied by Sergei Winogradsky co.pdfmalavshah9013
Explain why the organisms that were studied by Sergei Winogradsky could not be grown on
Robert Koch’s plate media containing agar or gelatin.
Solution
The organisms studied by Sergei Winogradsky are lithotrophs. Lithotrophs are the organisms
that need inorganic nutrients to synthesise the biomolecules necessary for the survival. Robert
Koch’s plate media containing agar or gelatin provides only organic nutrients. So, the lithotrophs
studied by Sergei Winogradsky could not be grown on Robert Koch’s plate media..
Electron transport powers the first steps of photosynthesis. The fo.pdfmalavshah9013
Electron transport powers the first steps of photosynthesis. The following diagram shows the
passage of electrons through the photosynthetic electron transport chain (ETC). a. What is the
source of the electrons (e) that enter Photosystem II (PSII)? What membrane are these
complexes embedded in? What is the final e^- acceptor for e^- leaving Photosystem I (PSI)?
(Please indicate both the unreduced and the reduced form of this acceptor) The light energy
captured by the photosynthetic reaction centers is used to establish a pH gradient across this
chloroplast membrane. (This means a gradient of H ions.) a. Indicate on the diagram above,
where the concentration of H is low and where it is high. How is this pH gradient established?
Specify at least 2 different ways. How is the H gradient (potential energy) used? What are the
products that the proton gradient made? Where in the chloroplast are they made?
Solution
Question number 1 :
A. In Higher plants, the ultimate source of the electrons passed to NADPH in plant (oxygenic)
photosynthesis is water. Photosynthetic bacteria use a variety of electron donors for this purpose
acetate, succinate, malate, or sulfide depending on what is available in a particular ecological
niche.
B. These photosystems are embedded in the thylokoid membranes. Higher plants contsins two
types of photosynthetic units associated with two different pigment systems, whcih obsorbs light
of different wavelengths.
C. The final electron acceptor in photosynthesis is NADP+, which is reduced to NADPH by
NADP reductase..
Describe 5 key traits the lung cancer cells within the primary tumor.pdfmalavshah9013
Describe 5 key traits the lung cancer cells within the primary tumor acquire and why they are
significant.
•As genetic stability is lost and genetic mutations accumulate some of these mutation result in
advantageous changes to cellular function. As a result, lung cancer cells acquire traits effective
for growth and development of tumors and invasion into surrounding tissue. Describe five of the
traits lung cancer cells have that are advantageous and justify why you chose those traits.
Solution
Thanks for the question
1. self-sufficiency in growth signals- the cell can keep growing by itself
2. insensitivity to growth-inhibitory (antigrowth) signals - the cell looses the ability to restrict its
unrestricted growth
3. evasion of programmed cell death (apoptosis),- the cell looses the ability of the body to evade
death and discard.
4. limitless replicative potential - the cell can keep on multiplying as much as it can without any
blocks or barriers
5. sustained angiogenesis- there is a constant and adequate emergence of blood supply for the
new grown tissues and cells
6. tissue invasion and metastasis. - the cancer cells are able to spread themselves into other
tissues physically and through blood
Each of these physiologic changes cause the successful transformation of non cancer cells to
cancer cells and make ineffective the anticancer defense mechanism present in the cells. These
six capabilities are shared in common by most and perhaps all types of human tumors.
Regards.
Complete the ANOVA tableSourceDFSSMSBetween Groups35.pdfmalavshah9013
Complete the ANOVA table
Source
DF
SS
MS
Between Groups
3
5
Within groups
12
337
total
472
How many groups were in the study
How many total observations were there
State the H0 and H1 and test at 5% level of significant
Source
DF
SS
MS
Between Groups
3
5
Within groups
12
337
total
472
Solution
How many groups were in the study
k = df1 + 1 = 3 + 1 = 4 [ANSWER]
*************
how many total observations were there
N = df1 + df2 + 1 = 3 + 12 + 1 = 16 [ANSWER]
********************
State the H0 and H1 and test at 5% level of significant
Ho: All the means in the 4 groups are equal.
Ha: At least 2 means in the 4 groups are different.
Here,
F = (SSB/df1) / (SSW/df2) = ((472-337)/3)/(337/12) = 1.602373887
As at 5%, df1 = 3, df2= 12,
Fcrit = 3.490294819
As F > Fcrit, we fail to reject Ho.
Thus, there is no significant evidence that at least 2 means are not equal. [CONCLUSION].
English Composition II - mutiple questions on researchQuestion 1 o.pdfmalavshah9013
English Composition II - mutiple questions on research
Question 1 of 10
Question 2 of 10
A. You write on a topic without many sources
B. You write about a local problem
C. You want to interview an expert
D. all of the above
Question 3 of 10
A. academic and trade journals
B. newspapers
C. press releases
D. govertment reports
Question 4 of 10
A. PDF documents
B. radio and TV broadcasts
C. press releases
D. academic journals
Question 5 of 10
A. web pages, PDF documents, ebooks
B. books, textbooks, ebooks
C. popular and academic journals, magazines, books
D. multimedia, newspapers, magazines
Question 6 of 10
Question 7 of 10
A. course failure
B. suspension
C. dismissal from the college
D. all of the above
Question 8 of 10
Question 9 of 10
Question 10 of 10
A. facilitating
B. fabricating
C. plagiarizing
D. none of the above
Question 1 of 105.0 Points The Internet is often the most convenient place to begin research but
not always the best. A. TrueB. False Reset Selection
Question 2 of 105.0 Points Primary research is useful when:
A. You write on a topic without many sources
B. You write about a local problem
C. You want to interview an expert
D. all of the above Reset Selection
Question 3 of 105.0 Points Where do you find the most up-to-date research and information in
business?
A. academic and trade journals
B. newspapers
C. press releases
D. govertment reports Reset Selection
Question 4 of 105.0 Points Multimedia includes:
A. PDF documents
B. radio and TV broadcasts
C. press releases
D. academic journals Reset Selection
Question 5 of 105.0 Points Traditional publications include:
A. web pages, PDF documents, ebooks
B. books, textbooks, ebooks
C. popular and academic journals, magazines, books
D. multimedia, newspapers, magazines Reset Selection
Question 6 of 105.0 Points Many traditional resources are now available online. A. TrueB.
False Reset Selection
Question 7 of 105.0 Points Violating the college\'s policy on academic honesty could result in:
A. course failure
B. suspension
C. dismissal from the college
D. all of the above Reset Selection
Question 8 of 105.0 Points Fabricating a source is an example of academic dishonesty. A.
TrueB. False Reset Selection
Question 9 of 105.0 Points To avoid plagiarism, you should change a few words in the source
material before paraphrasing. A. TrueB. False Reset Selection
Question 10 of 105.0 Points Submitting an assignment someone else has written and claiming it
as your own is called:
A. facilitating
B. fabricating
C. plagiarizing
D. none of the above
Solution
Ans(1):
A. True
Ans(2):
D. all of the above
Ans(3):
B. newspapers
Ans(4):
B. radio and TV broadcasts
Ans(5):
C. popular and academic journals, magazines, books
Ans(6):
A. True
Ans(7):
D. all of the above
Ans(8):
A. True
Ans(9):
B. False
Ans(10):
C. plagiarizing.
Customers arrive at a bank tellers booth at a rate of 2 per minute.pdfmalavshah9013
Customers arrive at a bank teller\'s booth at a rate of 2 per minute. What is the probability (to
four decimal places) that 4 customers will arrive at the bank teller\'s booth within the next minute
(assume a Poisson distribution)
Solution
Possion Distribution
PMF of P.D is = f ( k ) = e- x / x!
Where
= parameter of the distribution.
x = is the number of independent trials
P( X = 4 ) = e ^-2 * 2^4 / 4! = 0.0902.
Create a JAVA program that performs file IO and database interaction.pdfmalavshah9013
Create a JAVA program that performs file IO and database interaction via SQL. The program
needs to read data from the provided file: \"Project.csv\" and insert the data into a database. Then
the program needs to create a report from the database sorted by price descending. The report
should be in the format demonstrated below.
id (primary key - generated by the database)
cpuname
performance
price
Project.csv contents:CPU NamePerformancePrice (USD)Intel Core i7-3770K @
3.50GHz9,556$560.50Intel Core i7-3770 @ 3.40GHz9,327$335.55Intel Core i7-3820 @
3.60GHz8,990$404.38AMD FX-8350 Eight-Core8,940$149.99Intel Core i7-2600K @
3.40GHz8,501$379.97Intel Core i7-2600 @ 3.40GHz8,242$214.99Intel Core i7-4720HQ @
2.60GHz8,046NAAMD FX-8320 Eight-Core8,008$145.99Intel Core i7-6700HQ @
2.60GHz7,997$1509Intel Core i7-4710HQ @ 2.50GHz7,826NAIntel Core i5-6600K @
3.50GHz7,762$239.99Intel Core i7-4700HQ @ 2.40GHz7,754$383.00Intel Core i7-4700MQ
@ 2.40GHz7,736$467.40Intel Core i5-4690K @ 3.50GHz7,690$239.99AMD FX-8150 Eight-
Core7,619$165.99Intel Core i7-3630QM @ 2.40GHz7,604$304.49Intel Core i5-4670K @
3.40GHz7,598$249.99Intel Core i5-4690 @ 3.50GHz7,542$224.99Intel Core i7-3610QM @
2.30GHz7,460$399.99Intel Core i5-4670 @ 3.40GHz7,342$226.99Intel Core i5-4590 @
3.30GHz7,174$199.99Intel Core i7-4702MQ @ 2.20GHz7,146NAIntel Core i5-3570K @
3.40GHz7,130$477.23
Solution
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
public class Main
{
/**
* This the main function that runs at the start
* param args - input arguments from the command line
*/
static public void main(String[] args)
{
CPUList cpuList = new CPUList(); //The CPUList used to retrieve data from the
fiile and store in the db
CPUList cpuListRetrieved = new CPUList(); //The CPUList used to retrieve data from the
database
CpuDb cpuDb = new CpuDb(); //The database object used to move data to and
from the CPU Lists
try
{
//Read in the file and store each line into the CPU objects in a list
Files.lines(Paths.get(\"Project04Data.csv\"))
.map(line -> line.split(\"\ \ \")) // Stream
.flatMap(Arrays::stream) // Stream
.forEach(line -> cpuList.AddCpu(line));
//Clear the list table for the new listing
cpuDb.Clear();
//Insert the Cpu List into the database
cpuDb.SetCpuList(cpuList);
//Retrieve the Cpu List into a different CPU List object from the database
cpuDb.GetCpuList(cpuListRetrieved);
//Show the report from the new list that was retrieved from the database
cpuListRetrieved.ShowReport();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
CPUList.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public class CPUList
{
ArrayList theList = new ArrayList<>();
/**
* Default constructor for the CPU
*/
public void CPUList()
{
}
/**
* param strInputLine Input line to be used in creating the CPU object
*/
public void AddCpu(String strInputLine)
{
theList.add(new CPU(strInputLine));
}
/**
* param tempCPU - A CPU object to.
Wolves were hunted and poisoned to extinction in Sweden and Norway b.pdfmalavshah9013
Wolves were hunted and poisoned to extinction in Sweden and Norway by the mid-20th century.
Three wolves migrated from Russia and founded a new Scandinavian wolf population in the
early 1980s. That population now consists of approximately 100 animals. How large do you
think the Scandinavian wolf population should be to maintain genetic variation that may be
important for the viability (continued persistence) and continued evolution of this population?
There is some possibility of gene flow into this population from Russian wolves. Do you think
that it is important that gene flow between the Scandinavian and the Russian populations be
maintained in the future? Why?
Solution
There is no cut-off formula for calculating the length of population to maintain genetic diversity.
It is important to note that even after bottleneck effect populations are able to survive and are
able to maintain genetic diversity. Here, there are 100 animals; and these 100 animals are
heterozygous, not pure lines; because they have already mixed up with the Scandinavian
population. So, the population is large enough to maintain genetic variation.
Yes, there is further possibility of mixing of this population with Russian wolves further also; but
that possibility is very rare. This is so because wolves have already been extinct over there; as
per the question.
No, it is no more compulsion for gene flow between the two populations. This is so because the
populations have already diverged. And a subsequent amount of genetic variability has been
attained..
Describe the differences between OpenPGP, PGP and GPG.Solution.pdfmalavshah9013
Describe the differences between OpenPGP, PGP and GPG.
Solution
All the three mentioned are encryption method and stands for PGP - Pretty Good Privacy,
GPG(GNU Privacy Guard)
The difference between three could be below:
Availability in market - PGP is a licensed product whereas OpenPGP and GPG are freewares.
Functionality - PGP is a encyrption method that uses hashing,compression, cyrptography
concepts, OpenPgP is an encryption method which uses processes that are interoperatable with
PGP and GPG is a encryption method which provides a graphical inerface to encrypt files..
Declaring a PointerTo define a pointer, use an asterisk, (), in t.pdfmalavshah9013
Declaring a Pointer
To define a pointer, use an asterisk, (*), in the declaration to specify the variable will be a pointer
to the specified data type.
Recall that the name of an array holds the memory address of the first element of the array. The
second statement then would store the memory address of the first value in the variable valuePtr.
The name of a pointer is an identifier and must follow the rules for defining an identifier. Some
programmers place the letters ptr, a common abbreviation for pointer, at the end of the variable
name, others prefix a pointer with p_ or ptr_, and there are those who do nothing to distinguish a
pointer by its name. The naming of a pointer variable is a matter of programming style.
Once a pointer has been declared and initialized, it can be used to access the data to which it
points. In order to access this value, the dereference operator, *, must be used to prefix the name
of the pointer. From the code above, valuePtr holds the address of the first element of the values
array; therefore, *valuePtr will access the value 325. Add the following to main and execute the
program.
The output generated should look something like the following.
Where 0xbfad43e8 is a memory address displayed in hexadecimal.
Obtaining the Memory Address of a Variable
The address operator, &, is used to determine the memory address of a variable that is not an
array. Add code necessary to use fixed and setprecision, then add the following to main and run
the program to confirm the use of the address operator.
Using a Pointer to Alter Data
Just as the dereference operator is used to retrieve data, so too is it used to store data. Add the
following to function main and run the program.
The pointer, ratePtr, is used to change the data stored in payRate. The output of payRate
confirms the change.
Using a Pointer in an Expression
As previously shown, the value pointed to by a pointer variable can be retrieved by dereferencing
the pointer. In the above code, the retrieved value was simply displayed to the screen; however,
it can also be used in an expression. Add the following to main and execute the program.
Pointer Arithmetic
It is possible to add to or subtract from a memory address stored in a pointer. These actions can
be accomplished using the addition operator,+, subtraction operator, - and the increment and
decrement operators, ++ and --. This is helpful when accessing arrays via pointers.
The increment operator has been used to add the value 1 to a variable. When used with a pointer,
the increment operator adds the size of the data referenced to the memory address stored in the
pointer, effectively moving the pointer to the next data value. Building on the code from above,
add the following to main and execute the program.
We initialized valuePtr to the memory address of the first element of the array values.
Incrementing valuePtr instructs the computer to add four bytes, the size of an integer, to the
memory addressed stored in .
Who identified three key economic “advantages” that firms should hav.pdfmalavshah9013
Who identified three key economic “advantages” that firms should have for FDI to occur?
Hawthorne
Roosevelt
Dunning
Maslow
Forda.
Hawthorneb.
Rooseveltc.
Dunningd.
Maslowe.
Ford
Solution
Option \"C\" is correct.
Dunning identified the three key economic advantages that firms should have for FDI to occur:
1. Ownership advantages
2. Location advantages
3. Internalization advantages.
Which of these is the largesta. The surface zoneb. The mixed la.pdfmalavshah9013
Which of these is the largest?
a. The surface zone
b. The mixed layer
c. The deep zone
d. The bathypelagic zone
Solution
c. The bathypelagic zone ranges from 1000-4000m; that of the surface zone. i.e of epipalezic
zone is of 200m, the mixed layer or twilight or mesopalegic zone is of 200-1000m, and the deep
zone, hedapelazic zone is of approximately 5000m..
Which of the following concepts is exemplified by the story of Parus .pdfmalavshah9013
Which of the following concepts is exemplified by the story of Parus major and the island of
Vlieland? Gene flow reduces the genetic differences between populations. Gene flow can affect
how well populations are adapted to local environmental conditions. Genetic drift is significant
in small populations. Genetic drift can lead to a loss of genetic variation within populations.
Relative fitness is not the same as fitness when calculated on a 0-1 scale.
Solution
ANS: E. Relative fitness is not the same as fitness when calculated on a 0-1 scale.
Explanation:
Ex: the great tit (Parus major) on the Dutch island of Vlieland.
In Parus major high immigrated central region birds have a lower fitness, when compare with the
low immigration birds which are present in east. This phenomenon clearly explains low
immigrated birds had higher fitness.
Definitions of Other Terminology:
Darwin\'s fitness:
It is the ability of an individual to survive and reproduce in its environment.
Fitness of an organism is measured by how many offspring it produces compared to other
individuals of a species.
Adaptation refers to the trait that increases organism fitness relative to individuals without the
trait.
Genetic drift:
It is random and happens in every population due to chance. Because of this smaller population
are more susceptible to the effect of genetic drift.
Gene pool:
Gene pool is a reservoir of all genes, which was present in a population. Gene pool corresponds
with a number of unique alleles present in a population..
You will be implementing the following functions. You may modify the.pdfmalavshah9013
You will be implementing the following functions. You may modify the main to test the
functions, but this programwill work as a starting point.
//********** Function Prototypes ******************
//function isPrime
//input parameter - positive integer greater than 1
//returns true if the number is prime, otherwise false
//
bool isPrime (int number);
//function findPrimes
//input parameter - positive integer
//Uses the isPrime method to print a list of prime numbers between 1 and n.
void findPrimes (int n);
//function findFibo
//input parameter - positive integer
//returns the nth fibonacci number where
//Fib(0) -> 0
//Fib(1) -> 1
//Fib(N) -> Fib(N-2) + Fib(N-1)
//Note: You must use a loop in your solution. Also, if passed a 0, return 0.
int findFibo (int n);
//function findFactors
//input parameter - positive integer
//prints the prime factors of the given number to standard output (cout)
//example output: 52=2*2*13 (or 52=1*2*2*13) or 13=prime
//Hint: You will need nested loops for your solution.
void findFactors (int number);
Solution
#include
#include
using namespace std;
//********** Function Prototypes ******************
//function isPrime
//input parameter - positive integer greater than 1
//returns true if the number is prime, otherwise false
//
bool isPrime (int number);
//function findPrimes
//input parameter - positive integer
//Uses the isPrime method to print a list of prime numbers between 1 and n.
void findPrimes (int n);
//function findFibo
//input parameter - positive integer
//returns the nth fibonacci number where
//Fib(0) -> 0
//Fib(1) -> 1
//Fib(N) -> Fib(N-2) + Fib(N-1)
//Note: You must use a loop in your solution. Also, if passed a 0, return 0.
int findFibo (int n);
//function findFactors
//input parameter - positive integer
//prints the prime factors of the given number to standard output (cout)
//example output: 52=2*2*13 (or 52=1*2*2*13) or 13=prime
//Hint: You will need nested loops for your solution.
void findFactors (int number);
//****************** MAIN *****************************
int main ()
{
int testNum;
//test for the isPrime function
cout << \"Enter a test number - \";
cin >> testNum;
cout << endl;
if (isPrime(testNum))
cout << testNum << \" is prime.\" << endl;
else
cout << testNum << \" is not prime.\" << endl;
//test for how many primes
cout << \"Enter n to print the prime numbers between 1 and n: \";
cin >> testNum;
cout << endl;
findPrimes(testNum);
cout << endl;
//test for Fibonacci number finder
cout << \"Which Fibonacci number? \";
cin >> testNum;
cout << endl;
cout << \"The \" << testNum << \" Fibonacci number is : \" << findFibo(testNum) << endl;
cout << endl;
//test for prime factors
cout << \"Factor what number: \";
cin >> testNum;
cout << endl;
findFactors(testNum);
return 0;
}
//function isPrime
//input parameter - positive integer greater than 1
//returns true if the number is prime, otherwise false
//
bool isPrime (int number)
{
int c, f = 0;
if(number > 1)
{
for(c = 2; c < number; c++)
{
i.
When Elvis swims with the current, he swims 18km in 2 hours. Against.pdfmalavshah9013
When Elvis swims with the current, he swims 18km in 2 hours. Against the current, he can swim
only 14km in the same time. How fast can Elvis swim in still water and what is the rate of the
current?
Solution
D=RT
R=D/T
R=18/2=9 KMH WITH THE CURRENT.
R=14/2=7 KMH AGAINST THE CURRENT.
(9-7)/2=2/2=1 KMH IS THE SPEED OF THE CURRENT.
PROOF:
9-1=8 SWIMMER\'S SPEED.
7+1=8 DITTO.
What tarsal is lateral to the medial cuneiform What tarsal is .pdfmalavshah9013
What tarsal is lateral to the medial cuneiform?
What tarsal is lateral to the medial cuneiform?
Solution
Answer:
The tarsal bone lateral to the medial cuneiform is themiddle cuneiform (or the intermediate
cuneiform) .
There are seven tarsal bones and they are the calcaneus, talus, cuboid, navicular, and the medial,
middle, and lateral cuneiforms. Among the three cuneiforms, the medial cuneiform (also known
as first cuneiform) is the largest cuneiform bone. Lateral to the medial cuneiform is the middle
cuneiform and its lateral surface is marked by an inverted L-shaped facet along the posterior and
superior margins for the middle cuneiform bone..
What is the definition of memory access timeA. The difference bet.pdfmalavshah9013
What is the definition of memory access time?
A. The difference between read and write times
B, the time required to store data in the memory array
C. The time required to get valid output after a valid address is applied
D none of thee above
Also is read and times the same on typical computers the same or is one faster?
Solution
opptin B
Memory access time is how long it takes for a character in memory to be transferred to or from
the CPU.
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
How to Create Map Views in the Odoo 17 ERPCeline George
The map views are useful for providing a geographical representation of data. They allow users to visualize and analyze the data in a more intuitive manner.
Instructions for Submissions thorugh G- Classroom.pptxJheel Barad
This presentation provides a briefing on how to upload submissions and documents in Google Classroom. It was prepared as part of an orientation for new Sainik School in-service teacher trainees. As a training officer, my goal is to ensure that you are comfortable and proficient with this essential tool for managing assignments and fostering student engagement.
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.
This is a presentation by Dada Robert in a Your Skill Boost masterclass organised by the Excellence Foundation for South Sudan (EFSS) on Saturday, the 25th and Sunday, the 26th of May 2024.
He discussed the concept of quality improvement, emphasizing its applicability to various aspects of life, including personal, project, and program improvements. He defined quality as doing the right thing at the right time in the right way to achieve the best possible results and discussed the concept of the "gap" between what we know and what we do, and how this gap represents the areas we need to improve. He explained the scientific approach to quality improvement, which involves systematic performance analysis, testing and learning, and implementing change ideas. He also highlighted the importance of client focus and a team approach to quality improvement.
We all have good and bad thoughts from time to time and situation to situation. We are bombarded daily with spiraling thoughts(both negative and positive) creating all-consuming feel , making us difficult to manage with associated suffering. Good thoughts are like our Mob Signal (Positive thought) amidst noise(negative thought) in the atmosphere. Negative thoughts like noise outweigh positive thoughts. These thoughts often create unwanted confusion, trouble, stress and frustration in our mind as well as chaos in our physical world. Negative thoughts are also known as “distorted thinking”.
The LinkedList1 class implements a Linked list. class.pdf
1. /**
The LinkedList1 class implements a Linked list.
*/
class LinkedList1
{
/**
The Node class stores a list element
and a reference to the next node.
*/
private class Node
{
String value;
Node next;
/**
Constructor.
@param val The element to store in the node.
@param n The reference to the successor node.
*/
Node(String val, Node n)
{
value = val;
next = n;
}
/**
Constructor.
@param val The element to store in the node.
*/
Node(String val)
{
// Call the other (sister) constructor.
2. this(val, null);
}
}
private Node first; // list head
private Node last; // last element in list
/**
Constructor.
*/
public LinkedList1()
{
first = null;
last = null;
}
/**
The isEmpty method checks to see
if the list is empty.
@return true if list is empty,
false otherwise.
*/
public boolean isEmpty()
{
return first == null;
}
/**
The size method returns the length of the list.
@return The number of elements in the list.
*/
public int size()
{
3. int count = 0;
Node p = first;
while (p != null)
{
// There is an element at p
count ++;
p = p.next;
}
return count;
}
/**
The add method adds an element to
the end of the list.
@param e The value to add to the
end of the list.
*/
public void add(String e)
{
if (isEmpty())
{
first = new Node(e);
last = first;
}
else
{
// Add to end of existing list
last.next = new Node(e);
last = last.next;
}
}
/**
The add method adds an element at a position.
@param e The element to add to the list.
4. @param index The position at which to add
the element.
@exception IndexOutOfBoundsException When
index is out of bounds.
*/
public void add(int index, String e)
{
if (index < 0 || index > size())
{
String message = String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
// Index is at least 0
if (index == 0)
{
// New element goes at beginning
first = new Node(e, first);
if (last == null)
last = first;
return;
}
// Set a reference pred to point to the node that
// will be the predecessor of the new node
Node pred = first;
for (int k = 1; k <= index - 1; k++)
{
pred = pred.next;
}
// Splice in a node containing the new element
pred.next = new Node(e, pred.next);
// Is there a new last element ?
5. if (pred.next.next == null)
last = pred.next;
}
/**
The toString method computes the string
representation of the list.
@return The string form of the list.
*/
public String toString()
{
StringBuilder strBuilder = new StringBuilder();
// Use p to walk down the linked list
Node p = first;
while (p != null)
{
strBuilder.append(p.value + " ");
p = p.next;
}
return strBuilder.toString();
}
/**
The remove method removes the element at an index.
@param index The index of the element to remove.
@return The element removed.
@exception IndexOutOfBoundsException When index is
out of bounds.
*/
public String remove(int index)
{
if (index < 0 || index >= size())
{
6. String message = String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
String element; // The element to return
if (index == 0)
{
// Removal of first item in the list
element = first.value;
first = first.next;
if (first == null)
last = null;
}
else
{
// To remove an element other than the first,
// find the predecessor of the element to
// be removed.
Node pred = first;
// Move pred forward index - 1 times
for (int k = 1; k <= index -1; k++)
pred = pred.next;
// Store the value to return
element = pred.next.value;
// Route link around the node to be removed
pred.next = pred.next.next;
// Check if pred is now last
if (pred.next == null)
last = pred;
}
return element;
}
7. /**
The remove method removes an element.
@param element The element to remove.
@return true if the remove succeeded,
false otherwise.
*/
public boolean remove(String element)
{
if (isEmpty())
return false;
if (element.equals(first.value))
{
// Removal of first item in the list
first = first.next;
if (first == null)
last = null;
return true;
}
// Find the predecessor of the element to remove
Node pred = first;
while (pred.next != null &&
!pred.next.value.equals(element))
{
pred = pred.next;
}
// pred.next == null OR pred.next.value is element
if (pred.next == null)
return false;
// pred.next.value is element
pred.next = pred.next.next;
8. // Check if pred is now last
if (pred.next == null)
last = pred;
return true;
}
public static void main(String [] args)
{
LinkedList1 ll = new LinkedList1();
ll.add("Amy");
ll.add("Bob");
ll.add(0, "Al");
ll.add(2, "Beth");
ll.add(4, "Carol");
System.out.println("The members of the list are:");
System.out.print(ll);
}
}
/**
The DLinkedList class implements a doubly
Linked list.
*/
class DLinkedList
{
/**
The Node class stores a list element
and a reference to the next node.
*/
private class Node
{
String value; // Value of a list element
Node next; // Next node in the list
Node prev; // Previous element in the list
/**
9. Constructor.
@param val The element to be stored in the node.
@param n The reference to the successor node.
@param p The reference to the predecessor node.
*/
Node(String val, Node n, Node p)
{
value = val;
next = n;
prev = p;
}
/**
Constructor.
@param val The element to be stored in the node.
*/
Node(String val)
{
// Just call the other (sister) constructor
this(val, null, null);
}
}
private Node first; // Head of the list
private Node last; // Last element on the list
/**
Constructor.
*/
public DLinkedList()
{
first = null;
last = null;
10. }
/**
The isEmpty method checks to see if the list
is empty.
@return true if list is empty, false otherwise.
*/
public boolean isEmpty()
{
return first == null;
}
/**
The size method returns the length of the list.
@return The number of elements in the list.
*/
public int size()
{
int count = 0;
Node p = first;
while (p != null)
{
// There is an element at p
count ++;
p = p.next;
}
return count;
}
/**
The add method adds to the end of the list.
@param e The value to add.
*/
11. public void add(String e)
{
if (isEmpty())
{
last = new Node(e);
first = last;
}
else
{
// Add to end of existing list
last.next = new Node(e, null, last);
last = last.next;
}
}
/**
This add method adds an element at an index.
@param e The element to add to the list.
@param index The index at which to add.
@exception IndexOutOfBoundsException
When the index is out of bounds.
*/
public void add(int index, String e)
{
if (index < 0 || index > size())
{
String message = String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
// Index is at least 0
if (index == 0)
{
// New element goes at beginning
Node p = first; // Old first
12. first = new Node(e, p, null);
if (p != null)
p.prev = first;
if (last == null)
last = first;
return;
}
// pred will point to the predecessor
// of the new node.
Node pred = first;
for (int k = 1; k <= index - 1; k++)
{
pred = pred.next;
}
// Splice in a node with the new element
// We want to go from pred-- succ to
// pred--middle--succ
Node succ = pred.next;
Node middle = new Node(e, succ, pred);
pred.next = middle;
if (succ == null)
last = middle;
else
succ.prev = middle;
}
/**
The toString method computes the string
representation of the list.
@return The string representation of the
linked list.
*/
public String toString()
13. {
StringBuilder strBuilder = new StringBuilder();
// Use p to walk down the linked list
Node p = first;
while (p != null)
{
strBuilder.append(p.value + " ");
p = p.next;
}
return strBuilder.toString();
}
/**
The remove method removes the element
at a given position.
@param index The position of the element
to remove.
@return The element removed.
@exception IndexOutOfBoundsException When
index is out of bounds.
*/
public String remove(int index)
{
if (index < 0 || index >= size())
{
String message = String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
// Locate the node targeted for removal
Node target = first;
for (int k = 1; k <= index; k++)
target = target.next;
14. String element = target.value; // Element to return
Node pred = target.prev; // Node before the target
Node succ = target.next; // Node after the target
// Route forward and back pointers around
// the node to be removed
if (pred == null)
first = succ;
else
pred.next = succ;
if (succ == null)
last = pred;
else
succ.prev = pred;
return element;
}
/**
The remove method removes an element from the list.
@param element The element to remove.
@return true if the element was removed, false otherwise.
*/
public boolean remove(String element)
{
if (isEmpty())
return false;
// Locate the node targeted for removal
Node target = first;
while (target != null
&& !element.equals(target.value))
target = target.next;
15. if (target == null)
return false;
Node pred = target.prev; // Node before the target
Node succ = target.next; // Node after the target
// Route forward and back pointers around
// the node to be removed
if (pred == null)
first = succ;
else
pred.next = succ;
if (succ == null)
last = pred;
else
succ.prev = pred;
return true;
}
public static void main(String [] args)
{
DLinkedList ll = new DLinkedList();
ll.add("Amy");
ll.add("Bob");
ll.add(0, "Al");
ll.add(2, "Beth");
ll.add(4, "Carol");
System.out.println("The elements of the list are:");
System.out.println(ll);
}
}
Find the error
Find the error in correct in class below in each of the following code segments.
// Print the second element on
16. // a list myList of 3 elements
Node ref = myList; ref ++ ;
ref = ref.next;
System.out.print(ref.value);
2. // Print all elements in a list myList
Node ref = myList;
while (ref.next != null) {
System.out.print(ref.value + " "); }
3. // Add a node to the beginning of
// a doubly linked list
myList myList = new Node("Abraham", myList, null);
4. // Remove the first node of a nonempty
// doubly linked list
myList myList = myList.next;
5. // The reference last points to the last
// node in a nonempty doubly linked list.
// Remove the last node from the list l
ast = last.prev;
Algorithm Workbench
1. Write a recursive method void print(Node ref) that prints the values of all ele- ments in the
linked list whose first node is ref.
2. Write a nonrecursive method reverse() that reverses the order of the elements in a list.
Assume that this method is to be added to the LinkedList1 class in this chapter.
3. Write a method reverse() as in Algorithm Workbench 2, except implement the method to call
a private recursive method Node reverse(Node list). Implement this recursive method as well.
4. Add a method String removeMin() to the LinkedList1 class in this chapter. The method
removes and returns the minimum string (according to the usual dictionary order on strings) from
the list. If the list is empty, the method returns null.
Solution
1)
public void print(Node ref){
if(ref == null){
return;