The document outlines different data structures including linked lists, stacks, and queues. It describes how linked lists use self-referential nodes connected by links and can dynamically grow and shrink. Stacks are described as a constrained version of linked lists that only allow adding and removing from one end, with the push and pop methods.
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.
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
//.
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.
Sorted number list implementation with linked listsStep 1 Inspec.pdfalmaniaeyewear
Sorted number list implementation with linked lists
Step 1: Inspect the Node.java file
Inspect the class declaration for a doubly-linked list node in Node.java. Access Node.java by
clicking on the orange arrow next to LabProgram.java at the top of the coding window. The
Node class has three fields:
a double data value,
a reference to the next node, and
a reference to the previous node.
Each field is protected. So code outside of the class must use the provided getter and setter
methods to get or set a field.
Node.java is read only, since no changes are required.
Step 2: Implement the insert() method
A class for a sorted, doubly-linked list is declared in SortedNumberList.java. Implement the
SortedNumberList class's insert() method. The method must create a new node with the
parameter value, then insert the node into the proper sorted position in the linked list. Ex:
Suppose a SortedNumberList's current list is 23 47.25 86, then insert(33.5) is called. A new
node with data value 33.5 is created and inserted between 23 and 47.25, thus preserving the list's
sorted order and yielding: 23 35.5 47.25 86
Step 3: Test in develop mode
Code in main() takes a space-separated list of numbers and inserts each into a SortedNumberList.
The list is displayed after each insertion. Ex: If input is
then output is:
Try various program inputs, ensuring that each outputs a sorted list.
Step 4: Implement the remove() method
Implement the SortedNumberList class's remove() method. The method takes a parameter for the
number to be removed from the list. If the number does not exist in the list, the list is not
changed and false is returned. Otherwise, the first instance of the number is removed from the
list and true is returned.
Uncomment the commented-out part in main() that reads a second input line and removes
numbers from the list. Test in develop mode to ensure that insertion and removal both work
properly, then submit code for grading. Ex: If input is
then output is:
Given templates:
LabProgram.java
import java.util.Scanner;
import java.io.PrintWriter;
public class LabProgram {
// Prints the SortedNumberList's contents, in order from head to tail
public static void printList(SortedNumberList list) {
Node node = list.head;
while (null != node) {
System.out.print(node.getData() + " ");
node = node.getNext();
}
System.out.println();
}
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String inputLine;
// Read the line of input numbers
inputLine = scnr.nextLine();
// Split on space character
String[] terms = inputLine.split(" ");
// Insert each value and show the sorted list's contents after each insertion
SortedNumberList list = new SortedNumberList();
for (Object term : terms) {
double number = Double.parseDouble(term.toString());
System.out.println("List after inserting " + number + ": ");
list.insert(number);
printList(list);
}
/*
// Read the input line with numbers to remove
inputLine = scnr.nextLine();
terms = inputLine.split(" ".
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.
package singlylinkedlist; public class Node { public String valu.pdfamazing2001
package singlylinkedlist;
public class Node {
public String value;
public Node next;
public Node(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
SingleyLinkedList.java :
package singlylinkedlist;
import java.io.*;
import java.util.*;
/**
* Defines the interface for a singly-linked list.
*
*/
public interface SinglyLinkedList {
/**
* @return Reference to the first node. If the list is empty, this method
* returns null.
*/
public Node getFirst();
/**
* @return Reference to the last node . If the list is empty, this method
* returns null.
*/
public Node getLast();
/**
* @return Number of nodes in the list
*/
public int size();
/**
* @return true if the list has no nodes; false otherwise
*/
public boolean isEmpty();
/**
* Removes all nodes in the list.
*/
public void clear();
/**
* Inserts a new node with the given value after cursor.
*
* @param cursor
* The node to insert after. Set this to null to insert value as
the
* new first Node.
* @param value
* The value to insert
* @return a reference to the newly inserted Node
*/
public Node insert(Node cursor, String value);
/**
* Inserts a new node with the given value at the "end" of the list.
*
* @param value
* @return a reference to the newly inserted Node
*/
public Node append(String value);
/**
* Removes the node after the specified Node (cursor) from the list.
*
* @param cursor
* A reference to the Node to remove.
*/
public void removeAfter(Node cursor);
/**
* Returns a reference to the first Node containing the key, starting from
the
* given Node.
*
* @param start
* @param key
* @return a reference to the first Node containing the key
*/
public Node find(Node start, String key);
/**
* Prints the values of all the items in a list
*/
public void printWholeList();
}
SinglyLinkedTester.java:
package sbccunittest;
import static java.lang.Math.*;
import static java.lang.System.*;
import static org.apache.commons.lang3.StringUtils.*;
import static org.junit.Assert.*;
import static sbcc.Core.*;
import java.io.*;
import java.lang.reflect.*;
import java.nio.file.*;
import java.util.*;
import java.util.stream.*;
import org.apache.commons.lang3.*;
import org.junit.*;
import org.w3c.dom.ranges.*;
import sbcc.*;
import singlylinkedlist.*;
/**
* 09/16/2021
*
* @author sstrenn
*
*/
public class SinglyLinkedListTester {
public static String newline = System.getProperty("line.separator");
public static int totalScore = 0;
public static int extraCredit = 0;
public static boolean isZeroScore = false;
public static String scorePreamble = "";
@BeforeClass
public static void beforeTesting() {
totalScore = 0;
extraCredit = 0;
}
@AfterClass
public static void afterTesting() {
if (isZeroScore) {
totalScore = 0;
extraCredit = 0;
}
println(scorePreamble + "Estimated score (w/o late penalties, etc.) is:
" + totalScore + " out of 25.");
// If the project follows the naming convention, save the results in a
folder on
// the desktop. (Alex Kohanim)
try {
String directory =
substri.
Lecture 18Dynamic Data Structures and Generics (II).docxSHIVA101531
Lecture 18
Dynamic Data Structures and Generics (II)
*
*
Class ArrayListObject of an ArrayList can be used to store an unlimited number of objects.
*
Methods of ArrayList (I)
*
java.util.ArrayList
+ArrayList()
+add(o: Object) : void
+add(index: int, o: Object) : void
+clear(): void
+contains(o: Object): boolean
+get(index: int) : Object
+indexOf(o: Object) : int
+isEmpty(): boolean
+lastIndexOf(o: Object) : int
+remove(o: Object): boolean
+size(): int
+remove(index: int) : Object
+set(index: int, o: Object) : Object
Appends a new element o at the end of this list.
Adds a new element o at the specified index in this list.
Removes all the elements from this list.
Returns true if this list contains the element o.
Returns the element from this list at the specified index.
Returns the index of the first matching element in this list.
Returns true if this list contains no elements.
Returns the index of the last matching element in this list.
Removes the element o from this list.
Returns the number of elements in this list.
Removes the element at the specified index.
Sets the element at the specified index.
Creates an empty list.
Methods of ArrayList (II) Array is used to implement the methodsMethods get(int index) and set(int index, Object o) for accessing and modifying an element through an index and the add(Object o) for adding an element at the end of the list are efficient. Why?Methods add(int index, Object o) and remove(int index) are inefficient because it requires shifting potentially a large number of elements.
*
Linked Data StructureTo improve efficiency for adding and removing an element anywhere in a list.It containsCollection of objectsEach object contains data and a reference to another object in the collection
*
Linked ListA dynamic data structureA linked list consists of nodes. Each node contains an elementa link: linked to its next neighbor. Example: take notes in the class!
*
Linked List
*
ListNodes
ListNodes in Linked List
public class ListNode { // fill the comments
private String data; //
private ListNode link; //
/** */
public ListNode () {
link = null; //
data = null; //
}
/** */
public ListNode (String newData, ListNode linkValue) {
data = newData;
link = linkValue;
}
*
ListNodes in Linked List (cont’d)
/** */
public void setData (String newData) {
data = newData;
}
/** */
public String getData () {
return data;
...
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.
Exception to indicate that Singly LinkedList is empty. .pdfaravlitraders2012
/**
* Exception to indicate that Singly LinkedList is empty.
*/
class LinkedListEmptyException extends RuntimeException {
public LinkedListEmptyException() {
super();
}
public LinkedListEmptyException(String message) {
super(message);
}
}
/**
* Node class, which holds data and contains next which points to next Node.
*/
class Node {
public int data; // data in Node.
public Node next; // points to next Node in list.
/**
* Constructor
*/
public Node(int data) {
this.data = data;
}
/**
* Display Node\'s data
*/
public void displayNode() {
System.out.print(data + \" \");
}
}
/**
* Singly LinkedList class
*/
class LinkedList {
private Node first; // ref to first link on list
/**
* LinkedList constructor
*/
public LinkedList() {
first = null;
}
/**
* Insert New Node at first position
*/
public void insertFirst(int data) {
Node newNode = new Node(data); // Creation of New Node.
newNode.next = first; // newLink ---> old first
first = newNode; // first ---> newNode
}
/**
* Method deletes specific Node from Singly LinkedList in java.
*/
public Node deleteSpecificNode(int deleteKey) {
// Case1: when there is no element in LinkedList
if (first == null) { // means LinkedList in empty, throw exception.
throw new LinkedListEmptyException(
\"LinkedList doesn\'t contain any Nodes.\");
}
// Case2: when there is only one element in LinkedList- check whether we
// have to delete that Node or not.
if (first.data == deleteKey) { // means LinkedList consists of only one
// element, delete that.
Node tempNode = first; // save reference to first Node in tempNode-
// so that we could return saved reference.
first = first.next;
System.out.println(\"Node with data=\" + tempNode.data
+ \" was found on first and has been deleted.\");
return tempNode; // return deleted Node.
}
// Case3: when there are atLeast two elements in LinkedList
Node previous = null;
Node current = first;
while (current != null) {
if (current.data == deleteKey) {
System.out.println(\"Node with data=\" + current.data
+ \" has been deleted.\");
previous.next = current.next; // make previous node\'s next point
// to current node\'s next.
return current; // return deleted Node.
} else {
if (current.next == null) { // Means Node wasn\'t found.
System.out.println(\"Node with data=\" + deleteKey
+ \" wasn\'t found for deletion.\");
return null;
}
previous = current;
current = current.next; // move to next node.
}
}
return null;
}
/**
* Display Singly LinkedList
*/
public void displayLinkedList() {
System.out.print(\"Displaying LinkedList [first--->last]: \");
Node tempDisplay = first; // start at the beginning of linkedList
while (tempDisplay != null) { // Executes until we don\'t find end of
// list.
tempDisplay.displayNode();
tempDisplay = tempDisplay.next; // move to next Node
System.out.print(\"-->\");
}
System.out.println();
}
}
/**
* Main class - To test LinkedList.
*/
public class SinglyLinkedListDeleteNodeExample {
public static void main(String[] args) {
LinkedList linkedList = new LinkedList(); /.
Inspect the class declaration for a doubly-linked list node in Node-h-.pdfvishalateen
Inspect the class declaration for a doubly-linked list node in Node.h. Access Node.h by clicking
on the orange arrow next to main.cpp at the top of the coding window. The Node class has three
member variables: a double data value, a pointer to the next node, and a pointer to the previous
node. Each member variable is protected. So code outside of the class must use the provided
getter and setter member functions to get or set a member variable. Node.h is read only, since no
changes are required. Step 2: Implement the Insert() member function A class for a sorted,
doubly-linked list is declared in SortedNumberList.h. Implement the SortedNumberList class's
Insert() member function. The function must create a new node with the parameter value, then
insert the node into the proper sorted position in the linked list. Ex: Suppose a
SortedNumberList's current list is 23 47.25 86, then Insert(33.5) is called. A new node with data
value 33.5 is created and inserted between 23 and 47.25, thus preserving the list's sorted order
and yielding: 23 35.5 47.25 86 Step 3: Test in develop mode Code in main() takes a space-
separated list of numbers and inserts each into a SortedNumberList. The list is displayed after
each insertion. Ex: If input is 77 15 -42 63.5 then output is: List after inserting 77: 77 List after
inserting 15: 15 77 List after inserting -42: -42 15 77 List after inserting 63.5: -42 15 63.5 77 Try
various program inputs, ensuring that each outputs a sorted list. Step 4: Implement the Remove()
member function Implement the SortedNumberList class's Remove() member function. The
function takes a parameter for the number to be removed from the list. If the number does not
exist in the list, the list is not changed and false is returned. Otherwise, the first instance of the
number is removed from the list and true is returned. Uncomment the commented-out part in
main() that reads a second input line and removes numbers from the list. Test in develop mode to
ensure that insertion and removal both work properly, then submit code for grading. Ex: If input
is 84 72 19 61 19 84 then output is: List after inserting 84: 84 List after inserting 72: 72 84 List
after inserting 19: 19 72 84 List after inserting 61: 19 61 72 84 List after removing 19: 61 72 84
List after removing 84: 61 72
main.cpp
#include
#include
#include
#include "Node.h"
#include "SortedNumberList.h"
using namespace std; void PrintList(SortedNumberList& list); vector SpaceSplit(string source);
int main(int argc, char *argv[]) { // Read the line of input numbers string inputLine; getline(cin,
inputLine); // Split on space character vector terms = SpaceSplit(inputLine); // Insert each value
and show the sorted list's contents after each insertion SortedNumberList list; for (auto term :
terms) { double number = stod(term); cout << "List after inserting " << number << ": " << endl;
list.Insert(number); PrintList(list); } /* // Read the input line with numbers to remove getline(cin,
inputLi.
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
7. 20.4 Linked Lists (cont.) Fig 20.2 Linked list graphical representation. firstNode ... H D Q lastNode
8. List.java Lines 6-10 1 // Fig. 20.3: List.java 2 // ListNode and List class declarations. 3 package com.deitel.jhtp5.ch20; 4 5 // class to represent one node in a list 6 class ListNode { 7 8 // package access members; List can access these directly 9 Object data; 10 ListNode nextNode; 11 12 // create a ListNode that refers to object 13 ListNode( Object object ) 14 { 15 this ( object, null ); 16 } 17 18 // create ListNode that refers to Object and to next ListNode 19 ListNode( Object object, ListNode node ) 20 { 21 data = object; 22 nextNode = node; 23 } 24 25 // return reference to data in node 26 Object getObject() 27 { 28 return data; // return Object in this node 29 } 30 Self-referential class ListNode contains data and link to nextNode
9. List.java Line 41 Line 42 Line 55 31 // return reference to next node in list 32 ListNode getNext() 33 { 34 return nextNode; // get next node 35 } 36 37 } // end class ListNode 38 39 // class List declaration 40 public class List { 41 private ListNode firstNode; 42 private ListNode lastNode; 43 private String name; // string like "list" used in printing 44 45 // construct empty List with "list" as the name 46 public List() 47 { 48 this ( "list" ); 49 } 50 51 // construct an empty List with a name 52 public List( String listName ) 53 { 54 name = listName; 55 firstNode = lastNode = null ; 56 } 57 58 // insert Object at front of List 59 public synchronized void insertAtFront( Object insertItem ) 60 { Reference to first node in linked list Reference to last node in linked list First and last nodes in empty list are null
10. List.java Lines 61-62 Line 65 Lines 71-72 Line 74 Lines 81-82 61 if ( isEmpty() ) // firstNode and lastNode refer to same object 62 firstNode = lastNode = new ListNode( insertItem ); 63 64 else // firstNode refers to new node 65 firstNode = new ListNode( insertItem, firstNode ); 66 } 67 68 // insert Object at end of List 69 public synchronized void insertAtBack( Object insertItem ) 70 { 71 if ( isEmpty() ) // firstNode and lastNode refer to same Object 72 firstNode = lastNode = new ListNode( insertItem ); 73 74 else // lastNode's nextNode refers to new node 75 lastNode = lastNode.nextNode = new ListNode( insertItem ); 76 } 77 78 // remove first node from List 79 public synchronized Object removeFromFront() throws EmptyListException 80 { 81 if ( isEmpty() ) // throw exception if List is empty 82 throw new EmptyListException( name ); 83 84 Object removedItem = firstNode.data; // retrieve data being removed 85 86 // update references firstNode and lastNode 87 if ( firstNode == lastNode ) 88 firstNode = lastNode = null ; 89 else 90 firstNode = firstNode.nextNode; If list is not empty, the first node should refer to the newly inserted node If list is empty, the first and last node should refer to the newly inserted node If list is not empty, the last node should refer to the newly inserted node If list is empty, removing a node causes an exception If list is empty, the first and last node should refer to the newly inserted node
11. List.java Line 100 Lines 112-117 91 92 return removedItem; // return removed node data 93 94 } // end method removeFromFront 95 96 // remove last node from List 97 public synchronized Object removeFromBack() throws EmptyListException 98 { 99 if ( isEmpty() ) // throw exception if List is empty 100 throw new EmptyListException( name ); 101 102 Object removedItem = lastNode.data; // retrieve data being removed 103 104 // update references firstNode and lastNode 105 if ( firstNode == lastNode ) 106 firstNode = lastNode = null ; 107 108 else { // locate new last node 109 ListNode current = firstNode; 110 111 // loop while current node does not refer to lastNode 112 while ( current.nextNode != lastNode ) 113 current = current.nextNode; 114 115 lastNode = current; // current is new lastNode 116 current.nextNode = null ; 117 } 118 119 return removedItem; // return removed node data 120 121 } // end method removeFromBack If list is not empty, the second-to-last node becomes the last node If list is empty, removing a node causes an exception
12. List.java Lines 141-144 122 123 // determine whether list is empty 124 public synchronized boolean isEmpty() 125 { 126 return firstNode == null ; // return true if List is empty 127 } 128 129 // output List contents 130 public synchronized void print() 131 { 132 if ( isEmpty() ) { 133 System.out.println( "Empty " + name ); 134 return ; 135 } 136 137 System.out.print( "The " + name + " is: " ); 138 ListNode current = firstNode; 139 140 // while not at end of list, output current node's data 141 while ( current != null ) { 142 System.out.print( current.data.toString() + " " ); 143 current = current.nextNode; 144 } 145 146 System.out.println( "" ); 147 } 148 149 } // end class List Traverse list and print node values
13. EmptyListException.java Lines 5-19 1 // Fig. 20.4: EmptyListException.java 2 // Class EmptyListException declaration. 3 package com.deitel.jhtp5.ch20; 4 5 public class EmptyListException extends RuntimeException { 6 7 // no-argument constructor 8 public EmptyListException() 9 { 10 this ( "List" ); // call other EmptyListException constructor 11 } 12 13 // constructor 14 public EmptyListException( String name ) 15 { 16 super ( name + " is empty" ); // call superclass constructor 17 } 18 19 } // end class EmptyListException Exception thrown when program attempts to remove node from empty list
14. ListTest.java Line 10 Lines 13-16 Lines 19-26 1 // Fig. 20.5: ListTest.java 2 // ListTest class to demonstrate List capabilities. 3 import com.deitel.jhtp5.ch20.List; 4 import com.deitel.jhtp5.ch20.EmptyListException; 5 6 public class ListTest { 7 8 public static void main( String args[] ) 9 { 10 List list = new List(); // create the List container 11 12 // objects to store in list 13 Boolean bool = Boolean. TRUE ; 14 Character character = new Character( '$' ); 15 Integer integer = new Integer( 34567 ); 16 String string = "hello" ; 17 18 // insert references to objects in list 19 list.insertAtFront( bool ); 20 list.print(); 21 list.insertAtFront( character ); 22 list.print(); 23 list.insertAtBack( integer ); 24 list.print(); 25 list.insertAtBack( string ); 26 list.print(); 27 Create linked list Create values ( Object s) to store in linked-list nodes Insert values in linked list
15. ListTest.java Lines 30-44 28 // remove objects from list; print after each removal 29 try { 30 Object removedObject = list.removeFromFront(); 31 System.out.println( removedObject.toString() + " removed" ); 32 list.print(); 33 34 removedObject = list.removeFromFront(); 35 System.out.println( removedObject.toString() + " removed" ); 36 list.print(); 37 38 removedObject = list.removeFromBack(); 39 System.out.println( removedObject.toString() + " removed" ); 40 list.print(); 41 42 removedObject = list.removeFromBack(); 43 System.out.println( removedObject.toString() + " removed" ); 44 list.print(); 45 46 } // end try block 47 48 // catch exception if remove is attempted on an empty List 49 catch ( EmptyListException emptyListException ) { 50 emptyListException.printStackTrace(); 51 } 52 } 53 54 } // end class ListTest Remove values from linked list
16. ListTest.java Program Output The list is: true The list is: $ true The list is: $ true 34567 The list is: $ true 34567 hello $ removed The list is: true 34567 hello true removed The list is: 34567 hello hello removed The list is: 34567 34567 removed Empty list
17. 20.4 Linked Lists (cont.) Fig 20.6 Graphical representation of operation insertAtFront . firstNode 7 11 12 7 11 12 new Listnode firstNode new Listnode (a) (b)
22. StackInheritance.java Line 5 Lines 14-17 Lines 20-23 1 // Fig. 20.10: StackInheritance.java 2 // Derived from class List. 3 package com.deitel.jhtp5.ch20; 4 5 public class StackInheritance extends List { 6 7 // construct stack 8 public StackInheritance() 9 { 10 super ( "stack" ); 11 } 12 13 // add object to stack 14 public synchronized void push( Object object ) 15 { 16 insertAtFront( object ); 17 } 18 19 // remove object from stack 20 public synchronized Object pop() throws EmptyListException 21 { 22 return removeFromFront(); 23 } 24 25 } // end class StackInheritance StackInheritance extends List , because a stack is a constrained version of a linked list Method push adds node to top of stack Method pop removes node from top of stack
23. StackInheritanceTest.java Line 10 Lines 13-16 Lines 19-26 1 // Fig. 20.11: StackInheritanceTest.java 2 // Class StackInheritanceTest. 3 import com.deitel.jhtp5.ch20.StackInheritance; 4 import com.deitel.jhtp5.ch20.EmptyListException; 5 6 public class StackInheritanceTest { 7 8 public static void main( String args[] ) 9 { 10 StackInheritance stack = new StackInheritance(); 11 12 // create objects to store in the stack 13 Boolean bool = Boolean. TRUE ; 14 Character character = new Character( '$' ); 15 Integer integer = new Integer( 34567 ); 16 String string = "hello" ; 17 18 // use push method 19 stack.push( bool ); 20 stack.print(); 21 stack.push( character ); 22 stack.print(); 23 stack.push( integer ); 24 stack.print(); 25 stack.push( string ); 26 stack.print(); Create stack Create values ( Object s) to store in stack Insert values in stack
24. StackInheritanceTest.java Line 33 27 28 // remove items from stack 29 try { 30 Object removedObject = null ; 31 32 while ( true ) { 33 removedObject = stack.pop(); // use pop method 34 System.out.println( removedObject.toString() + " popped" ); 35 stack.print(); 36 } 37 } 38 39 // catch exception if stack is empty when item popped 40 catch ( EmptyListException emptyListException ) { 41 emptyListException.printStackTrace(); 42 } 43 } 44 45 } // end class StackInheritanceTest Remove object from stack
25. StackInheritanceTest.java Program Output The stack is: true The stack is: $ true The stack is: 34567 $ true The stack is: hello 34567 $ true hello popped The stack is: 34567 $ true 34567 popped The stack is: $ true $ popped The stack is: true true popped Empty stack com.deitel.jhtp5.ch20.EmptyListException: stack is empty at com.deitel.jhtp5.ch20.List.removeFromFront(List.java:82) at com.deitel.jhtp5.ch20.StackInheritance.pop( StackInheritance.java:22) at StackInheritanceTest.main(StackInheritanceTest.java:33)
26. StackComposition.java Lines 15-18 Lines 21-24 1 // Fig. 20.12: StackComposition.java 2 // Class StackComposition declaration with composed List object. 3 package com.deitel.jhtp5.ch20; 4 5 public class StackComposition { 6 private List stackList; 7 8 // construct stack 9 public StackComposition() 10 { 11 stackList = new List( "stack" ); 12 } 13 14 // add object to stack 15 public synchronized void push( Object object ) 16 { 17 stackList.insertAtFront( object ); 18 } 19 20 // remove object from stack 21 public synchronized Object pop() throws EmptyListException 22 { 23 return stackList.removeFromFront(); 24 } 25 Method push adds node to top of stack Method pop removes node from top of stack
27. StackComposition.java 26 // determine if stack is empty 27 public synchronized boolean isEmpty() 28 { 29 return stackList.isEmpty(); 30 } 31 32 // output stack contents 33 public synchronized void print() 34 { 35 stackList.print(); 36 } 37 38 } // end class StackComposition
28.
29. Queue.java Lines 15-18 Lines 21-24 1 // Fig. 20.13: Queue.java 2 // Class Queue. 3 package com.deitel.jhtp5.ch20; 4 5 public class Queue { 6 private List queueList; 7 8 // construct queue 9 public Queue() 10 { 11 queueList = new List( "queue" ); 12 } 13 14 // add object to queue 15 public synchronized void enqueue( Object object ) 16 { 17 queueList.insertAtBack( object ); 18 } 19 20 // remove object from queue 21 public synchronized Object dequeue() throws EmptyListException 22 { 23 return queueList.removeFromFront(); 24 } 25 Method enqueue adds node to top of stack Method dequeue removes node from top of stack
30. Queue.java 26 // determine if queue is empty 27 public synchronized boolean isEmpty() 28 { 29 return queueList.isEmpty(); 30 } 31 32 // output queue contents 33 public synchronized void print() 34 { 35 queueList.print(); 36 } 37 38 } // end class Queue
31. QueueTest.java Line 10 Lines 13-16 Lines 19-26 1 // Fig. 20.14: QueueTest.java 2 // Class QueueTest. 3 import com.deitel.jhtp5.ch20.Queue; 4 import com.deitel.jhtp5.ch20.EmptyListException; 5 6 public class QueueTest { 7 8 public static void main( String args[] ) 9 { 10 Queue queue = new Queue(); 11 12 // create objects to store in queue 13 Boolean bool = Boolean. TRUE ; 14 Character character = new Character( '$' ); 15 Integer integer = new Integer( 34567 ); 16 String string = "hello" ; 17 18 // use enqueue method 19 queue.enqueue( bool ); 20 queue.print(); 21 queue.enqueue( character ); 22 queue.print(); 23 queue.enqueue( integer ); 24 queue.print(); 25 queue.enqueue( string ); 26 queue.print(); Create queue Create values ( Object s) to store in queue Insert values in queue
32. QueueTest.java Line 33 27 28 // remove objects from queue 29 try { 30 Object removedObject = null ; 31 32 while ( true ) { 33 removedObject = queue.dequeue(); // use dequeue method 34 System.out.println( removedObject.toString() + " dequeued" ); 35 queue.print(); 36 } 37 } 38 39 // process exception if queue is empty when item removed 40 catch ( EmptyListException emptyListException ) { 41 emptyListException.printStackTrace(); 42 } 43 } 44 45 } // end class QueueCompositionTest Remove value from queue
33. QueueTest.java The queue is: true The queue is: true $ The queue is: true $ 34567 The queue is: true $ 34567 hello true dequeued The queue is: $ 34567 hello $ dequeued The queue is: 34567 hello 34567 dequeued The queue is: hello hello dequeued Empty queue com.deitel.jhtp5.ch20.EmptyListException: queue is empty at com.deitel.jhtp5.ch20.List.removeFromFront(List.java:88) at com.deitel.jhtp5.ch20.Queue.dequeue(Queue.java:23) at QueueTest.main(QueueTest.java:33)
34.
35.
36. 20.7 Trees (cont.) Fig 20.15 Binary tree graphical representation. B A D C
38. Tree.java Lines 9 and 11 Lines 24-32 1 // Fig. 20.17: Tree.java 2 // Declaration of class TreeNode and class Tree. 3 package com.deitel.jhtp5.ch20; 4 5 // class TreeNode declaration 6 class TreeNode { 7 8 // package access members 9 TreeNode leftNode; 10 int data; 11 TreeNode rightNode; 12 13 // initialize data and make this a leaf node 14 public TreeNode( int nodeData ) 15 { 16 data = nodeData; 17 leftNode = rightNode = null ; // node has no children 18 } 19 20 // locate insertion point and insert new node; ignore duplicate values 21 public synchronized void insert( int insertValue ) 22 { 23 // insert in left subtree 24 if ( insertValue < data ) { 25 26 // insert new TreeNode 27 if ( leftNode == null ) 28 leftNode = new TreeNode( insertValue ); 29 Left and right children If value of inserted node is less than value of tree node, insert node in left subtree
39. Tree.java Lines 35-43 30 else // continue traversing left subtree 31 leftNode.insert( insertValue ); 32 } 33 34 // insert in right subtree 35 else if ( insertValue > data ) { 36 37 // insert new TreeNode 38 if ( rightNode == null ) 39 rightNode = new TreeNode( insertValue ); 40 41 else // continue traversing right subtree 42 rightNode.insert( insertValue ); 43 } 44 45 } // end method insert 46 47 } // end class TreeNode 48 49 // class Tree declaration 50 public class Tree { 51 private TreeNode root; 52 53 // construct an empty Tree of integers 54 public Tree() 55 { 56 root = null ; 57 } 58 59 // insert a new node in the binary search tree 60 public synchronized void insertNode( int insertValue ) 61 { If value of inserted node is greater than value of tree node, insert node in right subtree
40. Tree.java Lines 81-93 62 if ( root == null ) 63 root = new TreeNode( insertValue ); // create the root node here 64 65 else 66 root.insert( insertValue ); // call the insert method 67 } 68 69 // begin preorder traversal 70 public synchronized void preorderTraversal() 71 { 72 preorderHelper( root ); 73 } 74 75 // recursive method to perform preorder traversal 76 private void preorderHelper( TreeNode node ) 77 { 78 if ( node == null ) 79 return ; 80 81 System.out.print( node.data + " " ); // output node data 82 preorderHelper( node.leftNode ); // traverse left subtree 83 preorderHelper( node.rightNode ); // traverse right subtree 84 } 85 86 // begin inorder traversal 87 public synchronized void inorderTraversal() 88 { 89 inorderHelper( root ); 90 } 91 Preorder traversal – obtain data, traverse left subtree, then traverse right subtree
41. Tree.java Lines 98-100 Lines 115-117 92 // recursive method to perform inorder traversal 93 private void inorderHelper( TreeNode node ) 94 { 95 if ( node == null ) 96 return ; 97 98 inorderHelper( node.leftNode ); // traverse left subtree 99 System.out.print( node.data + " " ); // output node data 100 inorderHelper( node.rightNode ); // traverse right subtree 101 } 102 103 // begin postorder traversal 104 public synchronized void postorderTraversal() 105 { 106 postorderHelper( root ); 107 } 108 109 // recursive method to perform postorder traversal 110 private void postorderHelper( TreeNode node ) 111 { 112 if ( node == null ) 113 return ; 114 115 postorderHelper( node.leftNode ); // traverse left subtree 116 postorderHelper( node.rightNode ); // traverse right subtree 117 System.out.print( node.data + " " ); // output node data 118 } 119 120 } // end class Tree Inorder traversal – traverse left subtree, obtain data, then traverse right subtree Postorder traversal – traverse left subtree, traverse right subtree, then obtain data
42. TreeTest.java Lines 15-19 Line 22 Line 25 1 // Fig. 20.18: TreeTest.java 2 // This program tests class Tree. 3 import com.deitel.jhtp5.ch20.Tree; 4 5 public class TreeTest { 6 7 public static void main( String args[] ) 8 { 9 Tree tree = new Tree(); 10 int value; 11 12 System.out.println( "Inserting the following values: " ); 13 14 // insert 10 random integers from 0-99 in tree 15 for ( int i = 1 ; i <= 10 ; i++ ) { 16 value = ( int ) ( Math.random() * 100 ); 17 System.out.print( value + " " ); 18 tree.insertNode( value ); 19 } 20 21 System.out.println ( "Preorder traversal" ); 22 tree.preorderTraversal(); // perform preorder traversal of tree 23 24 System.out.println ( "Inorder traversal" ); 25 tree.inorderTraversal(); // perform inorder traversal of tree Insert 10 random integers in tree Traverse binary tree via preorder algorithm Traverse binary tree via inorder algorithm
43. TreeTest.java Line 28 26 27 System.out.println ( "Postorder traversal" ); 28 tree.postorderTraversal(); // perform postorder traversal of tree 29 System.out.println(); 30 } 31 32 } // end class TreeTest Inserting the following values: 39 69 94 47 50 72 55 41 97 73 Preorder traversal 39 69 47 41 50 55 94 72 73 97 Inorder traversal 39 41 47 50 55 69 72 73 94 97 Postorder traversal 41 55 50 47 73 72 97 94 69 39 Traverse binary tree via postorder algorithm
44. 20.7 Trees (cont.) Fig 20.19 Binary search tree with seven values. 27 6 17 33 48 13 42