Example #1
0
void copyConstructorTester()
{
	LinkedQueue<string> queue;
   string items[] = {"zero", "one", "two", "three", "four", "five"};
	for (int i = 0; i < 6; i++)
   {
		cout << "Adding " << items[i] << endl;
      bool success = queue.enqueue(items[i]);
      if (!success)
         cout << "Failed to add " << items[i] << " to the queue." << endl;
	}
   cout << "Queue contains, from front to back, zero one two three four five." << endl;
   
   LinkedQueue<string> copyOfQueue(queue);
   cout << "Copy of queue contains, from front to back, ";
	for (int i = 0; i < 6; i++)
   {
      cout << " " << copyOfQueue.peekFront();
      copyOfQueue.dequeue();
   }
   cout << "." << endl;
   
   cout << "Original queue contains, from front to back,";
	for (int i = 0; i < 6; i++)
   {
      cout << " " << queue.peekFront();
      queue.dequeue();
   }
   cout << "." << endl << endl;
}  // end copyConstructorTester
void main()
{
	LinkedQueue LQ;
	string command;

	cout << "추가 : en, 제거 : de, 종료 : quit" << endl;

	while (true)
	{
		try
		{
			cin >> command;

			if (command.compare("en") == 0)
			{
				int data;
				cin >> data;
				LQ.enqueue(data);
			}
			else if (command.compare("de") == 0)
				LQ.dequeue();
			else if (command.compare("quit") == 0)
				return;

			LQ.show();
			cout << endl;
		}
		catch (const char *s)
Example #3
0
void LevelOrder(BinaryTreeNode<T> *t)
{// Level-order traversal of *t.
   LinkedQueue<BinaryTreeNode<T>*> Q;
   while (t) {
      Visit(t);  // visit t

      // put t's children on queue
      if (t->LeftChild) Q.Add(t->LeftChild);
      if (t->RightChild) Q.Add(t->RightChild);

      // get next node to visit
      try {Q.Delete(t);}
      catch (OutOfBounds) {return;}
      }
 }
Example #4
0
void AddLiveNode(LinkedQueue<T> &Q, T wt,
                    T& bestw, int i, int n)
{// Add node weight wt to queue Q if not leaf.
   if (i == n) {// feasible leaf
      if (wt > bestw) bestw = wt;}
   else Q.Add(wt); // not a leaf
}
Example #5
0
void Solver::addIfPossibleAndNotVissited(LinkedQueue<Cell*>& queue, Cell* pCell){
    
    if(pCell && !pCell->isVisited() && !pCell->isWall()){
        
        pCell->mark();
        queue.enqueue(pCell);
        
    }
}
Example #6
0
void CopyConstructorAndAssignmentTester() {
  LinkedQueue<string> queue;
  string items[] = {"zero", "one", "two", "three", "four", "five"};
  for (int i = 0; i < 6; i++) {
    cout << "Adding " << items[i] << endl;
    bool success = queue.Enqueue(items[i]);
    if (!success)
      cout << "Failed to add " << items[i] << " to the queue." << endl;
  }
  cout << "Queue contains, from front to back, zero one two three four five." << endl;
  
  cout << "Checking Copy Constructor tester " << endl;
  
  LinkedQueue<string> copy_of_queue(queue);
  cout << "Copy of queue contains, from front to back,";
  for (int i = 0; i < 6; i++)
    {
      cout << " " << copy_of_queue.PeekFront();
      copy_of_queue.Dequeue();
    }
  cout << "." << endl;
  
  cout << "Checking Assignment Operator tester " << endl;
  LinkedQueue<string> assigned_queue;
  assigned_queue.Enqueue("ha");
  assigned_queue.Enqueue("ba");
  assigned_queue = queue;
  cout << assigned_queue << endl;

  cout << "Assigned queue contains, from front to back, ";
  for (int i = 0; i < 6; i++)
    {
      cout << " " << assigned_queue.PeekFront();
      assigned_queue.Dequeue();
    }
  cout << "." << endl;
  
  cout << "Original queue contains, from front to back,";
  for (int i = 0; i < 6; i++) {
    cout << " " << queue.PeekFront();
    queue.Dequeue();
  }
  cout << "." << endl << endl;
}  // end copyConstructorTester
int main()
{
    LinkedQueue<string> frontmen;
    frontmen.enqueue("Dave Grohl");
    frontmen.enqueue("Bono");
    frontmen.enqueue("Chester Bennington");
    while (!frontmen.empty())
    {
        cout << frontmen.front() << endl;
        cout << frontmen.size() << endl;
        frontmen.dequeue();
    }
    return 0;
}
Example #8
0
T MaxLoading(T w[], T c, int n)
{// Return value of best loading.
 // Use FIFO branch and bound.
   // initialize for level 1 start
   LinkedQueue<T> Q;  // live-node queue
   Q.Add(-1);         // end-of-level marker
   int i = 1;         // level of E-node
   T Ew = 0,          // weight of E-node
     bestw = 0;       // best weight so far

   // search subset space tree
   while (true) {
      // check left child of E-node
      if (Ew + w[i] <= c) // x[i] = 1
         AddLiveNode(Q, Ew + w[i], bestw, i, n);

      // right child is always feasible
      AddLiveNode(Q, Ew, bestw, i, n); // x[i] = 0

      Q.Delete(Ew);     // get next E-node
      if (Ew == -1) {   // end of level
         if (Q.IsEmpty()) return bestw;
         Q.Add(-1);     // end-of-level marker
         Q.Delete(Ew);  // get next E-node
         i++;}          // level number of Ew
      }
}
Example #9
0
void Solver::getAllCells(Table matrix, Cell* startingCell){
    
    LinkedQueue<Cell*> linkedQueue;
    linkedQueue.enqueue(startingCell);
    
    Cell* newCell = NULL;
    while (!linkedQueue.isEmpty()) {
        
        Cell* curCell;
        linkedQueue.dequeue(curCell);
        curCell->mark();
        dArray.addElement(curCell);
        for(int index = 0; index < 4; ++index){
            
            if(matrix.validNextMove(curCell, index)){
                
                newCell = matrix.getElement(curCell->getRow() + dx[index], curCell->getCol() + dy[index]);
                addIfPossibleAndNotVissited(linkedQueue, newCell);
                
            }
        }
    }
}
Example #10
0
void horse_queue(Point start, Point end) {
	LinkedQueue<Position> q;
	q.enqueue(start);
	board[start.first][start.second] = true;
	Position current;
	LinkedStack<LinkedQueue<Position> > history;
	LinkedQueue<Position> level;
	int currentMove = 0;
	history.push(level);
	while (!q.empty() && (current = q.dequeue()).p != end) {
		if (current.move == currentMove) {
			history.peek().enqueue(current);
		} else {
			// current.move == currentMove + 1
			currentMove = current.move;
			LinkedQueue<Position> level;
			level.enqueue(current);
			history.push(level);
		}
		for(int dx = -2; dx <= 2; dx++)
			if (dx != 0)
				for(int sign = -1; sign <= 1; sign += 2) {
					int dy = sign * (3 - abs(dx));
					Point newstart(current.p.first + dx,
								   current.p.second + dy);
					Position newposition(newstart, current.move + 1);
					if (inside_board(newstart)
						&&
						!board[newstart.first][newstart.second]) {
						q.enqueue(newposition);
						clog << newposition << endl;
						board[newstart.first][newstart.second] = true;
					}

				}
	}
	// current == end -- успех
	// q.empty() -- неуспех
	clog << history;
	history.pop();
	if (current.p == end) {
		cout << "Успех за " << current.move << " хода!" << endl;
		LinkedStack<Point> path;
		path.push(current.p);
		while(!history.empty()) {
			// в history.peek() търсим първата позиция position,
			// за която isValidMove(current.p,position.p)
			Position position;
			while (!isValidMove(current.p,
					           (position = history.peek().dequeue()).p));
			// знаем, че isValidMove(current.p,position.p)
			// добавим position в пътя
			path.push(position.p);
			history.pop();
			current = position;
		}
		cout << path << endl;
	}
	else
		cout << "Неуспех!" << endl;
}
Example #11
0
int mains() {
   // Demonstrate that our LinkedQueue works.
   LinkedQueue numbers;

   numbers.Add(4);
   numbers.Add(8);
   numbers.Add(15);
   numbers.Add(16);
   numbers.Add(23);
   numbers.Add(42);

   while (numbers.Size() > 0) {
      int data = numbers.Remove();
      cout << "Removed " << data << endl;
   }
   // This seems to work! Yay!
   // But there are sinister bugs hidden from view...


   // First, what happened to the Nodes that got unlinked from the queue?



   // Second, what happens if I Remove from an empty queue?



   // Now that we've fixed those errors...
   // Third, what's up with this code?
   LinkedQueue second;
   second.Add(1);

   LinkedQueue copy = second; // make a copy of second
   copy.Add(2);
   cout << second.Size() << endl; // output: 1
   cout << copy.Size() << endl;   // output: 2

   second.Remove();
   copy.Remove();
   // whoops! What happened?





   // One final bug:
   if (true) {
      LinkedQueue third;
      third.Add(5);
      third.Add(6);

      // What happens when third goes out of scope?
      // What do we need to fix this?
   }

   for (int i = 0; i < 0; i++) {
      LinkedQueue temp;
      temp.Add(1);
      temp.Add(1);
      temp.Add(1);
      temp.Add(1);
      temp.Add(1);
   }

   LinkedQueue empty;
   cout << empty.Remove();
   return 0;
}
Example #12
0
bool FindPath(Position start, Position finish,
             int& PathLen, Position * &path)
{// Find a path from start to finish.
 // Return true if successful, false if impossible.
 // Throw NoMem exception if inadequate space.

   if ((start.row == finish.row) &&
      (start.col == finish.col))
         {PathLen = 0; return true;} // start = finish

   // initialize wall of blocks around grid
   for (int i = 0; i <= m+1; i++) {
      grid[0][i] = grid[m+1][i] = 1; // bottom & top
      grid[i][0] = grid[i][m+1] = 1; // left & right
      }

   // initialize offsets
   Position offset[4];
   offset[0].row = 0; offset[0].col = 1; // right
   offset[1].row = 1; offset[1].col = 0; // down
   offset[2].row = 0; offset[2].col = -1; // left
   offset[3].row = -1; offset[3].col = 0; // up

   int NumOfNbrs = 4; // neighbors of a grid position
   Position here, nbr;
   here.row = start.row;
   here.col = start.col;
   grid[start.row][start.col] = 2; // block
   
   // label reachable grid positions
   LinkedQueue<Position> Q;
   do {// label neighbors of here
      for (int i = 0; i < NumOfNbrs; i++) {
         nbr.row = here.row + offset[i].row;
         nbr.col = here.col + offset[i].col;
         if (grid[nbr.row][nbr.col] == 0) {
             // unlabeled nbr, label it
             grid[nbr.row][nbr.col]
                = grid[here.row][here.col] + 1;
             if ((nbr.row == finish.row) &&
                (nbr.col == finish.col)) break; // done
   	     Q.Add(nbr);} // end of if
         } // end of for
      
      // have we reached finish?
      if ((nbr.row == finish.row) &&
          (nbr.col == finish.col)) break; // done

      // finish not reached, can we move to a nbr?
      if (Q.IsEmpty()) return false; // no path
      Q.Delete(here); // get next position
   } while(true);
            
   // construct path
   PathLen = grid[finish.row][finish.col] - 2;
   path = new Position [PathLen];

   // trace backwards from finish
   here = finish;
   for (int j = PathLen-1; j >= 0; j--) {
      path[j] = here;
      // find predecessor position
      for (int i = 0; i < NumOfNbrs; i++) {
         nbr.row = here.row + offset[i].row;
         nbr.col = here.col + offset[i].col;
         if (grid[nbr.row][nbr.col] == j+2) break;
         }
      here = nbr;  // move to predecessor
      }

   return true;
}
Example #13
0
int main()
{
	ifstream inputFile;
	string fileName;  // Holds the user-inputted file name
	string fileLine;  // Holds the line extracted from the file
	string expression; // Holds the expression to be tested
	bool ableToOpen;  // Flag to see if file exists
	bool isBalanced;  // Flag for balanced expression

	cout << "Create queue object lq\n\n";
	LinkedQueue<string> lq;

	cout << "Get the fle input\n\n";
	do
	{	// Ask user for file name and attempt to open
		cout << "Enter input file name: ";
		cin >> fileName;
		ableToOpen = openFileIn(inputFile, fileName);
		if (!ableToOpen)
			cout << fileName << " cannot be opened." << endl;
	} while (!ableToOpen);

	// Read lines from the file and put into queue object
	getline(inputFile, fileLine);
	while (inputFile)
	{
		lq.enqueue(fileLine);
		getline(inputFile, fileLine);
	} // end while
	inputFile.close();

	cout << "\n\n\nAfter getting the file input, test other functions*******\n";
	cout << "Create lq1, a copy of the queue\n\n";
	LinkedQueue<string> lq1(lq);
	cout << "Display the contents of the copy queue lq1:\n";
	cout << lq1 << endl;

	cout << "\nAttempt to peek the now empty queue lq1:\n";
	try
	{
		lq1.peekFront();
	}
	catch (PrecondViolatedExcep e)
	{
		cout << e.what();
	}

	cout << "\nAssign lq to lq1 and then display lq1:\n";
	lq1 = lq;
	cout << lq1;

	cout << "\nPut the first string in lq into a stack of chars, ls1\n\n";
	LinkedStack<char> ls1;
	string firstLine = lq.peekFront();
	for (unsigned int i = 0; i < firstLine.length(); i++)
	{
		ls1.push(firstLine[i]);
	} // end for

	cout << "Create a copy, ls2, of the stack and display the copy:\n";
	LinkedStack<char> ls2(ls1);
	cout << ls2;

	cout << "\n\nAssign the first stack, ls1, to the second stack, ls2, and then display the second stack:\n";
	ls2 = ls1;
	cout << ls2;

	cout << "\n\n\n\nDo the expression checking:\n\n\n";
	while (!lq.isEmpty())
	{
		expression = lq.peekFront();
		lq.dequeue();
		cout << "The next string is:\t" << expression;
		isBalanced = checkExpression(expression);
		if (isBalanced)
			cout << "\tis a correct expression\n\n\n";
		else
			cout << "\tis NOT a correct expression\n\n\n";
	} // end while

	// Program Over
	cout << "Program Over\n\n";
	cin.ignore();
	cout << "Press Enter to end --> ";
	cin.ignore();
	cout << endl;
	return 0;
} // end main