Example #1
0
void make_sum_bigger(int n, int m, LinkedStack<int>& x, LinkedStack<int>& y, LinkedStack<int>& z){
int data_f = 0;
  for(int i=0;i<m ;i++){                       //Събира двета числа до позицията на по-малко
    data_f += x.pop() + y.pop();               //
    if(data_f < 10){
        z.push(data_f);
        data_f = 0; }
    else {
        z.push(data_f%10);
        data_f = 1;
    }
}
    int result = data_f;                  // и прехвърля останалите цифри (+1 ако има едно на ум) от по-голямото число в стека с резултата
    while(!x.empty()){
    result += x.pop();
    if (result >= 10){
    z.push(result % 10);
    result = 1;
    }
    else {
    z.push(result);
    result = 0;
    }
}
}
Example #2
0
void make_sum_small(int n, int m, LinkedStack<int>& x, LinkedStack<int>& y, LinkedStack<int>& z){
  //81094: Confusing bracket alignment within this function.
  int data = 0;
  for(int i=0;i<n;i++){
    data += x.pop() + y.pop();
    if(data < 10){
        z.push(data);
        data = 0; }
    else {
        z.push(data%10);
        data = 1;
    }
}   int result = data;
    while(!y.empty()){
    result += y.pop();
    if (result >= 10){
    z.push(result % 10);
    result = 1;
    }
    else {
    z.push(result);
    result = 0;
    }
}
}
Example #3
0
int main()
{ LinkedStack<int> numbers;
  try 
  { for (int i=10; i < 100; i+=10) numbers.push(i);
    while (!numbers.isEmpty()) cout << numbers.pop() << endl;
    numbers.pop();  
  }  
  catch(StackEmptyException e)
  {  cerr << e;
     return 1;
  }  
  return 0;    
}    
Example #4
0
void eval(LinkedStack& op, LinkedStack& num) {
    int numtop = num.top2();
    num.pop();
    if (op.top() == "+")
        numtop = add(num.top2(),numtop);
    else if (op.top() == "-")
        numtop = subtract(num.top2(),numtop);
    else if (op.top() == "*")
        numtop = multiply(num.top2(),numtop);
    else if (op.top() == "/")
        numtop = divide(num.top2(),numtop);
    op.pop(), num.pop();
    num.push(numtop);
}
int main() {

	LinkedStack<int> testLinkedStack;

	std::cout << "testLinkedStack.isEmpty() : " << testLinkedStack.isEmpty() << std::endl;
	std::cout << "testLinkedStack.getAllocatedSize() : " << testLinkedStack.getAllocatedSize() << std::endl;
	std::cout << "testLinkedStack.getSize() : " << testLinkedStack.getSize() << std::endl;

	testLinkedStack.push(5);
	testLinkedStack.push(6);
	testLinkedStack.push(7);
	testLinkedStack.push(9);
	testLinkedStack.push(10);

	std::cout << testLinkedStack.peek() << std::endl;

	int a = testLinkedStack.peek();
	testLinkedStack.pop();
	std::cout << a << std::endl;

	std::cout << testLinkedStack.peek() << std::endl;

	a = testLinkedStack.peek();
	testLinkedStack.pop();
	//testLinkedStack.pop(a);
	std::cout << a << std::endl;

	std::cout << testLinkedStack.peek() << std::endl;

	LinkedStack<int> testLinkedStack_2;
	testLinkedStack_2 = testLinkedStack;

	std::cout << testLinkedStack_2.peek() << std::endl;

	std::cout << "testLinkedStack.getSize() : " << testLinkedStack.getSize() << std::endl;

	testLinkedStack.clean();
	std::cout << "testLinkedStack.getSize() : " << testLinkedStack.getSize() << std::endl;
	std::cout << testLinkedStack.getAllocatedSize() << std::endl;

	testLinkedStack.push(5);
	testLinkedStack.push(6);
	std::cout << "testLinkedStack.getSize() : " << testLinkedStack.getSize() << std::endl;
	std::cout << testLinkedStack.peek() << std::endl;


	return 0;
}
Example #6
0
bool isBalanced(string brackets)		//O(N)
{
	LinkedStack bal = LinkedStack();
	int c1=0, c2=0, c3=0;
	string check;
	for(int i=0; i< brackets.size(); i++)
	{
		bal.push(brackets.substr(i,1));
	}
	
	for(int j=0; j<brackets.size(); j++)
	{
		check=bal.pop();
		if(check=="(") --c1;
		else if(check==")") ++c1;
		else if(check=="{") --c2;
		else if(check=="}") ++c2;
		else if(check=="[") --c3;
		else if(check=="]") ++c3;

		if(c1<0||c2<0||c3<0) return false;
	}
	//cout<<"c1: "<<c1<<" c2: "<<c2<<" c3: "<<c3<<endl;
	return (c1==0&&c2==0&&c3==0); 
}
Example #7
0
bool horse_rec(Point start, Point end,
			LinkedStack<Point>& path) {
	if (start == end) {
		path.push(end);
		cout << "Успех!" << endl;
		printPath(path);
		return true;
	}
	if (board[start.first][start.second])
		return false;
	board[start.first][start.second] = true;
	path.push(start);
	// !!! cout << start << endl;
	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(start.first + dx,
						       start.second + dy);
				if (inside_board(newstart) &&
					horse_rec(newstart, end, path))
					return true;

			}
	path.pop();
	return false;
}
Example #8
0
void printHistory(LinkedStack<LinkedStack<Point> >& history, ostream& os = cout) {
	if (!history.empty()) {
		Point x = history.pop().peek();
		printHistory(history);
		os << x << endl;
	}
}
Example #9
0
void make_sum(int n, int m, LinkedStack<int>& x, LinkedStack<int>& y, LinkedStack<int>& z){
//Kristian: Следващите 3 функции са напълно на 100% излишни. Можеше да използваш 2 stack-а и да направиш следното:
/*
int carryOver = 0;

while(!stack1.empty() || !stack2.empty()){
	int sum = stack1.top() + stack2.top() + carryOver;
	carryOver = sum/10 >= 0 ? 1 : 0;
	stack3.push(sum%10);
}

if(carryOver == 1)
	stack3.push(1);*/

if(n < m) {
        make_sum_small(n,m,x,y,z);           ///Първото число е по-голямо от второто
}
  else if (n > m){
        make_sum_bigger(n,m,x,y,z);       ///Второто число е по-голямо от първото
  }
 else {
       make_sum_equel(n,m,x,y,z);       ///Двете са равни
  }

    int p = 0;
    if (n>m)  p = n;
    else p = m;
    for(int i=0;i<p;i++){
    cout<<z.pop();
 }
}
Example #10
0
void printPath(LinkedStack<Point>& path, ostream& os = cout) {
	if (!path.empty()) {
		Point x = path.pop();
		printPath(path, os);
		os << x << endl;
	}
}
Example #11
0
void  make_sum_equel(int n, int m, LinkedStack<int>& x, LinkedStack<int>& y, LinkedStack<int>& z){

    int data_s = 0;                            ///пази допълнителната еденица
      for(int i=0;i<m-1;i++){
    data_s += x.pop() + y.pop();
    if(data_s < 10) {
        z.push(data_s);
        data_s = 0; }
    else {
        z.push(data_s %10);
        data_s = 1;
    }
}
  data_s += x.pop() + y.pop();
  z.push(data_s);
}
Example #12
0
void testPointStack() {
	LinkedStack<Point2D<int> > s;
	s.push(Point2D<int>(1, 2));
	s.push(Point2D<int>(2, 3));
	s.push(Point2D<int>(3, 4));
	while (!s.empty())
		cout << s.pop();
}
Example #13
0
void generate_numbers(int n, int m, LinkedStack<int>& first, LinkedStack<int>& second){
   int random_f, random_s;
   for (int i=0;i<n;i++){                   ///Представяне със свързан стек като всяка кутийка пази едноцифрено число
    if(i==0){
        random_f = rand() %9 + 1;
        first.push(random_f);
    }
    else {
        random_f = rand() %10;
        first.push(random_f);
    }
   }

    for (int i=0;i<m;i++){
    if(i==0){
        random_s = rand() %9 + 1;
        second.push(random_s);
    }
    else {
        random_s = rand() % 10;
        second.push(random_s);
    }
   }
LinkedStack<int> copy_of_first ;
LinkedStack<int> copy_of_second ;
LinkedStack<int> help = first;

 cout<<"First number: ";                   ///обръщане на стека, използвайки помощен стек
 for(int i=0; i<n; i++){
    copy_of_first.push(help.pop());
 }
 for(int i=0; i<n; i++){
    cout<<copy_of_first.pop();
 }
 cout<<endl;
 cout<<"Second number: ";
 help = second;
 for(int i=0; i<m; i++){
    copy_of_second.push(help.pop());
 }
 for(int i=0;i<m;i++){
    cout<<copy_of_second.pop();
 }
cout <<endl;
}
Example #14
0
void testStackTemplate() {
	LinkedStack<double> ls;
	ls.push(1.8);
	cout << ls.pop() << endl;

	LinkedStack<Point2D<double> > sp;
	Point2D<double> p(1,2);
	sp.push(p);
}
Example #15
0
bool is_balanced(string brackets)
{
  if(brackets == "") return true;
  LinkedStack ls;
  for (unsigned i = 0; i < brackets.size() ; i++)
  {
    string c = brackets.substr(i,i+1);
    if(c == "[" || c == "(" || c == "{")
    {
      ls.push(c);
    }
    else if(c == "]" )
    {
      if(ls.top() == "[")
      {
        ls.pop();
      }
      else return false;
    }
    else if(c == "}")
    {
      if(ls.top() == "{")
      {
        ls.pop();
      }
    }
    else if( c == ")" )
    {
      if(ls.top() == "(")
      {
        ls.pop();
      }
      else return false;
    }
    else 
    {
      if(ls.isEmpty()) return true;
    }
  }
  if(ls.isEmpty()) return true;
  return false;
}
Example #16
0
int main()
{
	int x;
	LinkedStack<int> intStack;

	for( int i = 0 ; i < 22 ; i++)
		intStack.push( i*2);

	intStack.printStack();
	intStack.pop( x);

	cout << "After pop" << endl;
	intStack.printStack();

	return 0;
}
bool isHtmlMatched(const vector<string>& tags) {
  LinkedStack<string> S;
  typedef vector<string>::const_iterator Iter;

  for (Iter p = tags.begin(); p != tags.end(); ++p) {
    if (p->at(1) != '/')
      S.push(*p);
    else {
      if (S.empty()) return false;
      string open = S.top().substr(1);
      string close = p->substr(2);
      if (open.compare(close) != 0) return false;
      else S.pop();
    }
  }
  if (S.empty()) return true;
  else return false;
}
Example #18
0
void horse_stack(Point start, Point end) {
	LinkedStack<LinkedStack<Point> > history;
	LinkedStack<Point> startStack;
	ofstream clog("log.txt");
	startStack.push(start);
	history.push(startStack);
	while (!history.empty() &&
			(history.peek().empty() || history.peek().peek() != end)) {
		if (history.peek().empty()) {
			// Стъпка назад
			history.pop();
			if (!history.empty())
				history.peek().pop();
			clog << "Стъпка назад" << endl;
		}
		else {
			// стъпка напред
			Point current = history.peek().peek();
			clog << "Стъпка напред: " << current << endl;
			LinkedStack<Point> possibleMoves;
			board[current.first][current.second] = true;
			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.first + dx,
									   current.second + dy);
						if (inside_board(newstart)
							&&
							!board[newstart.first][newstart.second])
							possibleMoves.push(newstart);
					}
			LinkedStack<Point> pm(possibleMoves);
			clog << "---\n";
			printPath(pm,clog);
			clog << endl << "---\n";
			history.push(possibleMoves);
		}
	}
	if (!history.empty() && !history.peek().empty()) {
		cout << "Успех:\n";
		printHistory(history);
	}
}
Example #19
0
/*
The main entry point for the program.
*/
int main ( int argc, const char * argv[] )
{
    char input;
    LinkedStack s;

    while ( !cin.eof() )
    {
        cout << "Please enter a string." << endl;
        while ( cin.get ( input ) && input != ( char ) '\n' )
        {
            s.push ( input );
        }

        while ( !s.isEmpty() )
        {
            cout << s.pop();
        }

        cout << endl;
    }
}
Example #20
0
bool checkParentheses(char const* s) {
	LinkedStack<char> stack;
	char const* p = s;
	while (*p != '\0') {
		switch (*p) {
		case '(':
		case '[':
		case '{':
		case '<':
			stack.push(*p);
			break;
		case ')':
		case ']':
		case '}':
		case '>':
			if (stack.empty() ||
				!matchParentheses(stack.pop(), *p))
				return false;
			break;
		}
		p++;
	}
	return stack.empty();
}
Example #21
0
int main()
{
	LinkedStack<int> stack = LinkedStack<int>();
	for (int i = 0; i < 10; i = i + 2)
	{
		stack.push(i);
		std::cout << stack.peek() << std::endl;
	}
	try
	{
		for (int i = 0; i < 10; i++)
		{
			int topValue = stack.pop();
			std::cout << topValue << std::endl;
		}
	}
	catch (std::exception e)
	{
		std::cout << e.what() << std::endl;
	}


	return 0;
}
Example #22
0
bool checkExpression(const string& expression)
{
	LinkedStack<char> balancedStack;
	bool balancedSoFar = true;
	unsigned int i = 0;  // Used to keep track of position in expression
	int singleQuote = 0, doubleQuote = 0;  // Used to keep track of delimiters ' and "
	char ch;  // Holds character at position i in expression

	while ( balancedSoFar && (i < expression.length()) )
	{
		// Get first character in expression, then increment position
		ch = expression[i];
		i++;

		switch (ch)
		{	
			// Skip next character if escape character is found
			case '\\':
				i++;
				break;

			// Push an open token
			case '{':
			case '[':
			case '(':
				balancedStack.push(ch);
				break;
			case '\'':
			{
				singleQuote++;
				if (singleQuote % 2 == 0)
					balancedStack.pop();  // Pop matching delimiter
				else
					balancedStack.push(ch);
				break;
			} // end ' case
			case '"':
			{
				doubleQuote++;
				if (doubleQuote % 2 == 0)
					balancedStack.pop();  // Pop matching delimiter
				else
					balancedStack.push(ch);
				break;
			} // end " case
			
			// Close tokens
			case '}':
			case ']':
			case ')':
			{
				// Make sure stack is not empty and the close token matches the open
				if (!balancedStack.isEmpty() && 
					(  (balancedStack.peek() == '(') 
					|| (balancedStack.peek() == '{')
					|| (balancedStack.peek() == '[') ) )
					balancedStack.pop();  // Pop a matching closed token
				else                      // No matching closed token
					balancedSoFar = false;
				break;
			}
		} // end switch
	} // end while

	if ( !(balancedSoFar && balancedStack.isEmpty()) )
		balancedSoFar = false;

	return balancedSoFar;
} // end checkExpression
Example #23
0
int main()
{
    bool stay = true;

    // create one instance for each of the test classes

    cout << "\nInstanciate an object of LinkedStack\n";
    LinkedStack<string>* stackPtr = new LinkedStack<string>();

    cout << "\nProgram started, \n"
         << "    initiate the TEST DRIVER with a set of hard-wired data!\n"
         << "For example, \n"
         << "    you may use this set of tokens as a default test case: \n"
         << "    the, items, are, 123, 456, 789, and, abc";

    string choice; // user input for choices

    // initialize the LinkedStack class instances
    stackPtr->push("the");
    stackPtr->push("items");
    stackPtr->push("are");
    stackPtr->push("123");
    stackPtr->push("456");
    stackPtr->push("789");
    stackPtr->push("and");
    stackPtr->push("abc");
    cout << "\n   Use the P - peek command to view the stack.\n";

    // main menu while
    while(stay) {  // main menu while starts
        menu();
        stay = true;
        cin >> choice;
        cin.ignore();

        if(choice.size() == 1) {
            char ch = choice[0];
            vector<string> dump;
            string value;
            switch(ch) {  // main menu switch starts

            case 'd': // display stack
            case 'D':
                if(stackPtr->isEmpty()) {
                    cout << "\n		Stack is empty.\n";
                } else {
                    stackPtr->displayStack();
                }
                break;

            case 'e': // is stack empty?
            case 'E':
                if(stackPtr->isEmpty())
                {
                    cout << "\n		The list is empty\n";
                } else {
                    cout << "\n		There are items in the stack\n";
                }
                break;

            case 'i': // insert item
            case 'I':
                cout << "		insert item: ";
                cin >> value;
                stackPtr->push(value);
                break;

            case 'r': // remove item
            case 'R':
                if(stackPtr->isEmpty())
                {
                    cout << "\n		The list is empty\n";
                } else {
                    stackPtr->pop();
                    cout << "\n		Top item removed.\n";
                }
                break;

            case 'c': // clear stack
            case 'C':
                // to be completed by you;
                if(stackPtr->isEmpty()) {
                    cout << "\n		Stack already empty.\n";
                } else {
                    stackPtr->clear();
                }

                break;

            case 'p': // peek TOP value
            case 'P':
                cout << "\n		The top value is: " << stackPtr->peek() << endl;
                break;

            case 'q': // quit main menu
            case 'Q':
                stay = false;
                break;

            default:
                cout << "\nInvalid Selection!\nTry again!\n\n";
            } // end of menu switch
        } // only process single character
    } // end of main menu while
Example #24
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;
}