본문 바로가기
C++/0x06-algorithm

stack

by SpeeDr00t 2016. 8. 3.
반응형

stack

1.소스

#include <iostream>
#include <queue>

using namespace std;

// User defined stack that uses a queue
class Stack
{
public:

    queue<int>q;

public:
    void push(int val);
    void pop();
    int top();
    bool empty();
};



// Push operation
void Stack::push(int val)
{
    // Get previous size of queue
    int s = q.size();

    // Push current element
    q.push(val);

    // Pop (or Dequeue) all previous
    // elements and put them after current
    // element
    for (int i=0; i<s; i++)
    {
        // this will add front element into
        // rear of queue
        q.push(q.front());

        // this will delete front element
        q.pop();
    }
}




// Removes the top element
void Stack::pop()
{

    if (q.empty()) { 

        cout << "No elements\n";

    }else{

        q.pop();
    }
}




// Returns top of stack
int Stack::top()
{
    return (q.empty())? -1 : q.front();
}




// Returns true if Stack is empty else false
bool Stack::empty()
{
    return (q.empty());
}




// Driver code
int 
main( int argc , char ** argv )
{
    Stack s;
    s.push(10);
    s.push(20);
    cout << s.top() << endl;

    s.pop();
    s.push(30);
    s.pop();
    cout << s.top() << endl;

return 0;
}


결과

hacker@ubuntu:~/c$ 
hacker@ubuntu:~/c$ 
hacker@ubuntu:~/c$ g++ -o stack1 stack1.cpp 
hacker@ubuntu:~/c$ 
hacker@ubuntu:~/c$ 
hacker@ubuntu:~/c$ ./stack1 
20
10
hacker@ubuntu:~/c$ 
hacker@ubuntu:~/c$ 
반응형

'C++ > 0x06-algorithm' 카테고리의 다른 글

pattern matching  (0) 2016.08.03
Round Robin Scheduling Algorithm  (0) 2016.07.14