C++ Hashing, binary tree rotating, and fenceposting.

Dec 17th, 2015
RockCafe
Category:
Computer Science
Price: $125 USD

Question description

2 questions, URGENT NEEDS TO BE DONE TONIGHT. Please copy and paste all code answers and screenshots of output.


Question 1:

The program below has all the code needed for the options in the main menu other than option 6 which is to change value of the user’s input string.  You must add code for option 6 into the code below. 

These are the action that must happen when the user chooses option 6:

1) the code must accept both values from the user - the existing value and the replacement value.

2) the program has to calculate the hash values of both values.

3) the code must retrieve the existing entry and delete it from its place on its current list.

4) change the user value in the in-memory copy of the entry

5) use the replacement hash value to place the entry on the appropriate list in the data structure.

#include <iostream>
#include <string>
using namespace std;
#define MAX 7  // specify the number of array elements to be available
class Node {
public:
   Node () {}
   Node* putOneNode (Node*, string);
   string getOneNode ();
   Node* getNextPointer ();
   void putNextPointer (Node*);
private:
   string str;
   Node* nextPtr;
};
#include <cstdlib>
Node* Node::getNextPointer (){
   return nextPtr;
}
void Node::putNextPointer (Node* x){
   this->nextPtr = x;
}
Node* Node::putOneNode (Node* x, string s) {
   Node* temp;
   temp = new Node();
   if (temp) {
     temp->nextPtr = x;
     temp->str = s;
   }
   return temp;
}
string Node::getOneNode() {
   return str;
}
class HashList {
public:
   HashList ();
   bool putNode (string);
   void displayList ();
   Node* findNode (string);
   void  deleteNode (string);
   Node* getListPointer();
private:
   Node* ListPointer;
};
//#include "Node.h"
//#include "HashList.h"
#include <cstdlib>
#include <iostream>
using namespace std;
HashList::HashList ()
   {ListPointer = NULL;}
bool HashList::putNode (string udata) {
   bool x = false;
   Node A;
   Node* temp1;
   temp1 = A.putOneNode (ListPointer, udata);
   if (temp1 != NULL)
   {   ListPointer = temp1;
     x = true;
   }
   return x;
}
Node* HashList::getListPointer () {
   return ListPointer;
   }
Node* HashList::findNode (string udata){
   Node* temp;
   for (temp = ListPointer; temp != NULL && temp->getOneNode() != udata;
      temp = temp->getNextPointer());
   return temp;
}
void HashList::displayList() {
   Node* temp;
   for (temp = ListPointer; temp != NULL;
                   temp = temp->getNextPointer())
     cout << " " <<temp->getOneNode ();
   cout << endl;
}
void HashList::deleteNode (string udata) {
   Node* delPtr = findNode (udata);
   if (delPtr != NULL) {
     if (ListPointer == delPtr)
       ListPointer = delPtr->getNextPointer();
     else {    
       Node* previousPtr;
       Node* temp = ListPointer;
       for (previousPtr = NULL; temp != delPtr;
         previousPtr = temp, temp = temp->getNextPointer());
       previousPtr->putNextPointer(delPtr->getNextPointer());
     }
     delete delPtr;
   }
   else
     cout << "Invalid data entered" << endl;
}
int main () {  // 1
   int sel;
   char buffer2[80];  // input buffer
   char buffer3[80];  // input buffer
   int hashValue, modHash, i;
   bool cont = true;
   HashList namePtr [MAX];
   while (!cin.eof() && cin.good() && cont == true) {
    cout << "Enter your function: 1 add, 2 list, 3 exit, 4 find, 5 delete, 6 change value of entry: ";
    cin >> sel;
    if (!cin.eof() && cin.good() ) {
    switch (sel) {   
     case 1: {
       cout << "Please enter a string of characters followed by <Enter>: " << endl;
       cin >> buffer2;  // get user input string -- less than 80 characters
       if (!cin.eof()) {  // accept user input
         hashValue = 0;
         for (i = 0; i < strlen (buffer2); i++){ //4  // calculate hash value by adding the ASCII
           hashValue += (int) buffer2[i];  //  equivalents of the user's input characters
           }
         modHash = hashValue % MAX;         // reduce hash value to be within the table
         namePtr[modHash].putNode (buffer2);
         }
       else
         {
         cont = false;
         }
       break;
       }
     case 2: {
       for (i = 0; i < MAX; i++) { // list the contents of the array of lists
         if(namePtr[i].getListPointer()) {
           cout << "List number is " << i << " Attached List follows " << endl;
           namePtr[i].displayList();
           }
         }
       break;
       }
     case 3: {
       cont = false;
       break;
       }
     case 4: {
       cout << "Please enter user value to find " << endl;
       cin >> buffer2;  // get user input string -- less than 80 characters
       if (!cin.eof()) {  // accept user input
         hashValue = 0;
         for (i = 0; i < strlen (buffer2); i++){ //4  // calculate hash value by adding the ASCII
           hashValue += (int) buffer2[i];  //  equivalents of the user's input characters
           }
       modHash = hashValue % MAX;         // reduce hash value to be within the table
       if (namePtr[modHash].getListPointer()){  // Use getListPointer method to get onto target list
         cout << "List " << modHash << " at location " << namePtr[modHash].getListPointer()
            << " contains ";  // report list header at target location
         namePtr[modHash].displayList(); // report list at target location
         cout << "User value " << buffer2 << " is at location "
           << namePtr[modHash].findNode (buffer2) << endl; //Report target entry and its location
         }
       else
         cout << "List " << modHash << " is empty." << endl;
        }
       break;     
       }
     case 5: {
       cout << "Please enter user value to delete " << endl;
       cin >> buffer2;  // get user input string -- less than 80 characters
       if (!cin.eof()) {  // accept user input
         hashValue = 0;
         for (i = 0; i < strlen (buffer2); i++){ //4  // calculate hash value by adding the ASCII
           hashValue += (int) buffer2[i];  //  equivalents of the user's input characters
           }
       modHash = hashValue % MAX;         // reduce hash value to be within the table
       if (namePtr[modHash].getListPointer()){  // (Bugfix) use getListPointer method to get onto target list
         if (namePtr[modHash].findNode (buffer2))
           namePtr[modHash].deleteNode (buffer2);
           }
         else
           cout << "Entry " << buffer2 << " not found." << endl;
         }
       break;
       }
     case 6: {
       cout << " Option to Change value not yet implemented." << endl;
       break;
       }
     default: {
       cout << "Invalid selection." << endl;
          }
       }
     }
   }
return 0;
}



Question 2: 

The following variables in the code below are selected to fencepost: root, subroot, pivot  and parentRoot in those methods. 

In the code below for the RotateRight method, you will see that there is inserted fenceposting throughout the module in order to capture the values which have been posted for the objects which are referenced by the variables root, subroot, pivot and parentRoot.

The display number 1 is appropriate because it displays the incoming parameter value subroot and the module which it references.  The fenceposting for display 4 has been done correctly with its “before” and “after” strings.  However, for displays 2 and 3 and 5 thru 13, found in void BST::rotateRight(Node* subRoot), the displays have only been done after the updates.  

1)  Please insert the proper displays before the updates into the RotateRight code.  Then, compile and run the program using the following names as input data:  Walter, Louise, Arthur. These values will cause the RotateRight method to be executed only once after Arthur is entered. Please provide a screenshot of the output.


#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <string>
//#include "node.h"
//#include "bintree.h"
using namespace std;

class Node {
private:
  string val; // user input provides value in collating sequence
  Node* lh; // pointer to left-hand descendant Node
  Node* rh; // pointer to right-hand descendant Node
  Node* parent; //pointer to parent Node or NULL if root Node
public:
    Node () { lh = rh = parent = NULL; val = ""; }
  void  putVal (string v) { val = v; }
  string getVal () { return val; }
  void  putLH (Node* x) { lh = x; }
  Node*  getLH () { return lh; }
  void  putRH (Node* x) { rh = x; }
  Node*  getRH () { return rh; }
  void  setParent(Node* x) {parent = x;}
  Node*  getParent() {return parent;}
};

class BST { // Container for Binary Search Tree
private:
  int count;
  Node* root;
  Node* tree;
private:
  Node* addNode (Node*, string);
  Node* findInsertion (Node* tree, string v);
  void inOrder (Node*);
  void preOrder (Node*);
  void postOrder (Node*);
  void locate (Node*, string);
  void rotateRight (Node*);
  void rotateLeft (Node*);
  void postInsertionBalance (Node*);
  void treeDisplay (Node*, int);
  void displayANode (int, Node*, string);
public:
  BST ();
  void addRootNode (string);
  void inOrderTraverse ();
  void preOrderTraverse ();
  void postOrderTraverse ();
  int  getCount () { return count; }
  void locateRoot (string);
  int  balanceFactor(Node*);
  int  subTreeHeight(Node*);
  void treeDisplayRoot();
};

BST::BST () { // Default Constructor
   root = tree = NULL; count = 0;
}

void BST::addRootNode (string v)
{ if (root == NULL)
  {
    root = tree = addNode (tree, v);
  }
  else
  { tree = root;
  tree = findInsertion (tree, v);
  }
}

Node* BST::findInsertion (Node* tree, string v)
{ string x;
  x = tree -> getVal();
  //cout << count << " compare " << v << " and " << x << endl;
  if ( v < x ) //look to left of cureent node
  if( tree -> getLH () !=NULL )
  { tree = findInsertion (tree -> getLH(), v);
   return tree;     // *** from Paul Pollack 11/13/13 *** prevent
             // a new node from being added twice
  }
  else
  { Node* temp = NULL;
     temp = addNode (temp, v);
     tree ->putLH(temp);
     temp ->setParent(tree); //added functionality for parents
     postInsertionBalance(temp); //balance the tree
  }
  else if ( v > x )  // look to right of current node
  if (tree -> getRH () !=NULL )
  { tree = findInsertion (tree -> getRH(), v);
     return tree;  // from Paul Pollack 11/13/13 same as above
  }
  else
  { Node* temp = NULL;
     temp = addNode (temp, v);
     tree ->putRH(temp);
     temp ->setParent(tree);  //added functionality for parents
     postInsertionBalance(temp); //balance the tree
  }
  else
    cout << "Node " << x << " found -- already in Binary Tree." << endl;
  return tree;
}
Node* BST::addNode (Node* x, string v)
{ if (x = new Node)
  { x->putVal (v);
  ++count;
  x->putLH(NULL);
  x->putRH(NULL);
  x->setParent(NULL);
  }
  return x;
}
void BST::displayANode (int i, Node* y, string nodeName)
   { cout << "(" << i << ") " << y -> getVal () << "\t";
    if ((y -> getVal ()).size() < 4)  
        cout << "\t";
  cout << nodeName << " in Node at " << (int)y;
    cout << " LC " << (int)y->getLH() << " RC " << (int)y->getRH();
    cout << " Parent " << (int)y->getParent();
    cout << endl;
  }
void BST::locateRoot (string v) {
  if ( root == NULL )
  cout << "Tree is empty" << endl;
  else
  locate ( root, v );
}
void BST::locate (Node* y, string v) {  // Bug mentioned by Dan Glade
  string x;
  x = y -> getVal ();
  if ( v == x )
  { cout << "Value " << v << " is in Node at reference " << (int)y << endl;
    cout << " Left Child ref " << (int)y->getLH() << "  Right Child ref " << (int)y->getRH();
    cout << "  Parent ref " << (int)y->getParent() << endl;
  }
  else if ( v < x )
  if ( y -> getLH() != NULL )
  locate (y-> getLH(), v);
  else
  cout << "Value not in tree" << endl;
  else // if ( v > x )
  if ( y -> getRH() != NULL )
  locate ( y-> getRH(), v );
  else
  cout << "Value not in tree" << endl;
}
void BST::inOrderTraverse ()
{ cout << endl;
  inOrder (root);
}
void BST::inOrder (Node* n)
{ if (n != NULL) {
  inOrder (n->getLH());
  cout << n->getVal() << endl;
  inOrder (n->getRH());
  }
  return;
}
void BST::preOrderTraverse ()
{ cout << endl;
  preOrder (root);
}
void BST::preOrder (Node* n)
{ if (n == NULL) return;
  cout << n->getVal() << endl;
  preOrder (n->getLH());
  preOrder (n->getRH());
}
void BST::postOrderTraverse ()
{ cout << endl;
  postOrder (root);
}
void BST::postOrder (Node* n)
{ if (n != NULL) //return;
  { postOrder (n->getLH());
  postOrder (n->getRH());
  cout << n->getVal() << endl;
  }
}
void BST::treeDisplayRoot() {
  treeDisplay(root, 0);
}

void BST::treeDisplay(Node* ref, int depth) {
  // from Main & Savitch page 506
  cout << setw(4*depth) << ""; // indentation
  if (ref == NULL) {
  // reached a NULL reference in an interior node
  cout << "[NULL]" << endl;
  } else if (ref->getLH() == NULL && ref->getRH() == NULL) {
  // a leaf
  cout << "Value " << ref->getVal() << " at Ref " << (int) ref;
  cout << " [leaf]" << endl;
  } else {
  // a nonleaf - interior node
   if ( depth == 0 )
     cout << "  Root  0 ";
  cout << "Value " << ref->getVal() << " at Ref " << (int) ref << endl;
   cout << "Left Child  " << depth+1;
  treeDisplay(ref->getLH(), depth + 1);
   cout << "Right Child " << depth+1;
  treeDisplay(ref->getRH(), depth + 1);
  }
}
// This BST procedure uses rotations to do AVL-balance whenever a Node is added.  
// In order to do this in all levels of the tree, it calculates a balance
// factor, and uses this to determine when to rotate Nodes of the tree.  The
// rotations are made so as to preserve the navigation of the tree.
// The AVL balancing technique allows us to circumvent the problem of balancing
// the input (more about this later in the course), when we can rebalance the
// tree after each node is added. However, the AVL technique consumes much
// overhead. For ease of programming, nodes now keep track of their parents to
// facilitate the rotating procedure.
// Note that the AVL technique does not handle the problem of deleting a Node
// from a BST.

int BST::balanceFactor(Node* n)  //Added by Jeremy Wright
{
  return subTreeHeight(n->getLH()) - subTreeHeight(n->getRH());
}

int BST::subTreeHeight(Node* n) //tells the height of the larger subtree under this node.
{
  int subHeightL;
  int subHeightR;
  if(n == NULL)
  {
  return -1;
  }
  if(n->getLH() == NULL)
  {
  if(n->getRH() == NULL)
     {
      return 0;
     }
  else
     {
      subHeightR = subTreeHeight(n->getRH())+1;
      return subHeightR;
     }
  }
  else if(n->getRH() == NULL)
  {
  subHeightL = subTreeHeight(n->getLH())+1;
  return subHeightL;
  }
  else
  {
  subHeightL = subTreeHeight(n->getLH()) + 1;
  subHeightR = subTreeHeight(n->getRH()) + 1;
  if(subHeightL > subHeightR)
     {
      return subHeightL;
     }
  else
     {
      return subHeightR;
     }
  }
}
void BST::rotateRight(Node* subRoot)  //rotates a tree right, with subRoot as
    // its original root and pivot as the new root
{ cout << endl << "Begin rotateRight" << endl;
  displayANode (1, subRoot, "subRoot param");
  Node* pivot = NULL;
  cout << "2  pivot before contains Null" << endl;
  pivot = subRoot->getLH();  //new root of this subtree is the left child
  // cout << "pivot is " << (int) pivot << endl;
  displayANode (2, pivot, "pivot after");
  Node* parentRoot = NULL;
  cout << "3  parentRoot before contains NULL" << endl;
  parentRoot = subRoot->getParent();  //store parent of subtree
  // cout << "parentRoot is " << (int) pivot << endl;
  if (parentRoot != NULL)
    displayANode (3, parentRoot, "parentRoot after");
  else
    cout << "(3A)  Ref subRoot" << (int) subRoot << " is Root Node -- No Parent " << endl;
  displayANode (4, subRoot, "subRoot before");
  subRoot->putLH(pivot->getRH());  //the root takes the right child of the pivot
                   // to preserve BST structure
  displayANode (4, subRoot, "subRoot after");
  if(subRoot->getRH() != NULL)
  {
    displayANode (5, subRoot, "subRoot before");
    subRoot->getRH()->setParent(subRoot);  //make sure child knows its parent
    displayANode (5, subRoot, "subRoot after");
  }
  displayANode (6, pivot, "pivot before");
  pivot->putRH(subRoot); //the root becomes the right child of the pivot
  displayANode (6, pivot, "pivot after");
  displayANode (7, subRoot, "subRoot before");
  subRoot->setParent(pivot);
  displayANode (7, subRoot, "subRoot after");
 
  if(subRoot == root)
  {
    displayANode (8, root, "root before");
    root = pivot;
    displayANode (8, root, "root after");
    displayANode (9, pivot, "pivot before");
    pivot->setParent(NULL);
    displayANode (9, pivot, "pivot after");
  }
  else  //connect subtree to its parent
  {
  if(parentRoot->getLH() == subRoot)
     {
      displayANode (10, parentRoot, "parentRoot before");
      parentRoot->putLH(pivot);
      displayANode (10, parentRoot, "parentRoot after");
      displayANode (11, pivot, "pivot before");
      pivot->setParent(parentRoot);
      displayANode (11, pivot, "pivot after");
     }
  else
     {
      displayANode (12, parentRoot, "parentRoot before");
      parentRoot->putRH(pivot);
      displayANode (12, parentRoot, "parentRoot after");
      displayANode (13, pivot, "pivot before");
      pivot->setParent(parentRoot);
      displayANode (13, pivot, "pivot after");
     }
  }
  cout << "End of rotateRight" << endl;
}
void BST::rotateLeft(Node* subRoot) //Rotates tree left as Rotate_Right
{ cout << endl << "Begin rotateLeft" << endl;
  displayANode (1, subRoot, "subRoot");
  Node* pivot = subRoot->getRH();   
  displayANode (2, pivot, "pivot");
  Node* parentRoot = subRoot->getParent();
  if (parentRoot != NULL)
    displayANode (3, parentRoot, "parentRoot");
  else
    cout << "(3A)  Ref subRoot " << (int) subRoot << " is Root Node -- No Parent " << endl;
  subRoot->putRH(pivot->getLH());
  if(subRoot->getRH() != NULL)
  {
  subRoot->getRH()->setParent(subRoot);
  displayANode (4, subRoot, "subRoot");
  }
  displayANode (5, subRoot, "subRoot");
  pivot->putLH(subRoot);
  displayANode (6, pivot, "pivot");
  subRoot->setParent(pivot);
  displayANode (7, subRoot, "subRoot");
  if(subRoot == root) // Need to test if entire tree is balanced!!!
  {
  root = pivot;
    displayANode (8, root, "root");
  pivot->setParent(NULL);
    displayANode (9, pivot, "pivot");
  }
  else
  {
  if(parentRoot->getLH() == subRoot)
     {
      parentRoot->putLH(pivot);
      displayANode (10, parentRoot, "parentRoot");
      pivot->setParent(parentRoot);
      displayANode (11, pivot, "pivot");
     }
  else
     {
      parentRoot->putRH(pivot);
      displayANode (12, parentRoot, "parentRoot");
      pivot->setParent(parentRoot);
      displayANode (13, pivot, "pivot");
     }
  }
  cout << "End of rotateLeft" << endl;
}
void BST::postInsertionBalance (Node* n)  //Run after every insertion to
   // balance the tree.  Any imbalances can be dealt with by looking at
   // the parent line to root of the new Node as mentioned above.
{ Node* p;
  if(balanceFactor(n) == 2)
  {
  p = n->getLH();
  if(balanceFactor(p) == -1)
     {
      rotateLeft(p);
     }
  rotateRight(n);
  }
  else if(balanceFactor(n) == -2)
  {
  p = n->getRH();
  if(balanceFactor(p) == 1)
     {
      rotateRight(p);
     }
  rotateLeft(n);
  }
  if(n != root) //run until we travel up to root
  {
  postInsertionBalance(n->getParent());
  }
}

int main () {
  string x;
  char op = ' ';
  char confirm = ' ';
  BST TREE;
  //Node* test;
  // Create inorder Binary treee
  cout << "To create your Binary tree, use the menu below." << endl << endl;
  cout << "Enter your operation using the capital letter shown in your selection." << endl;
  cout << "Add a node, display a Node, Show sorted list, display Tree, Help, Exit: " << endl;
  while (!cin.eof() && op != 'E' && op != 'e')  // build binary tree in this loop
  { cout << "Enter your operation: ";
  cin >> op;
  if (!cin.eof () && op != 'E' && op != 'e')
   switch (op)
    {
    case 'A': case 'a':
    { cout << "Enter your string: ";
    cin >> x;
    if (!cin.eof())
         TREE.addRootNode (x);
    break;
    }
    case 'S': case 's':
    {if ( TREE.getCount ())
       { cout << endl << "In-OrderTree Traversal" << endl;
        TREE.inOrderTraverse ();
//        cout << "Pre-Order Tree Traversal" << endl << endl;
//        TREE.preOrderTraverse();
//        cout << "Post-Order Tree Traversal" << endl << endl;
//        TREE.postOrderTraverse();
       }
    break;
    }
    case 'N': case 'n':
    { cout << endl << "Enter User value of Node to Display: ";
    cin >> x;
    if (!cin.eof())
        { TREE.locateRoot ( x );
        cout << endl;
      }
    break;
    }
    case 'T': case 't':
     {if ( TREE.getCount ())
       { cout << endl << "Display Tree:" << endl;
        TREE.treeDisplayRoot ();
       }
     else
       cout << endl << "Tree is empty. No entries found.";
    cout << endl;
     break;
     }
    case 'H': case 'h':
     { cout << "Enter your operation using the capital letter shown in your selection." << endl;
      cout << "Add a node, display a Node, Show sorted list, display Tree, Help, Exit" << endl;
      break;
     }
    case 'E': case 'e':
    { break;
    }
    default:
    { cout << "Invalid operation. Try again!" << endl;
      cout << "Operations are " << endl;
      cout << "Add a node, display a Node, Show sorted list, display Tree, Help, Exit" << endl;
    break;
    }
    }
  }
  system("PAUSE");
  return EXIT_SUCCESS;
}


Tutor Answer

(Top Tutor) Daniel C.
(997)
School: Cornell University
PREMIUM TUTOR

Studypool has helped 1,244,100 students

3 Reviews


Summary
Quality
Communication
On Time
Value
BlueOcean
Nov 15th, 2016
" Awesome! Exactly what I wanted. "
ashleyisgod
Oct 24th, 2016
" Top quality work from this guy! I'll be back! "
Molly_Moon
Oct 1st, 2016
" AMAZING as always! "
Ask your homework questions. Receive quality answers!

Type your question here (or upload an image)

1831 tutors are online

Brown University





1271 Tutors

California Institute of Technology




2131 Tutors

Carnegie Mellon University




982 Tutors

Columbia University





1256 Tutors

Dartmouth University





2113 Tutors

Emory University





2279 Tutors

Harvard University





599 Tutors

Massachusetts Institute of Technology



2319 Tutors

New York University





1645 Tutors

Notre Dam University





1911 Tutors

Oklahoma University





2122 Tutors

Pennsylvania State University





932 Tutors

Princeton University





1211 Tutors

Stanford University





983 Tutors

University of California





1282 Tutors

Oxford University





123 Tutors

Yale University





2325 Tutors