Question #5779

Implement a as stack and a queue using arrays.

Expert's answer

#include <iostream>

using namespace std;

const int SIZE = 10000;

struct Stack

{

int arr[SIZE];

int k;

Stack() : k(0) { }

void push(int a)

{

& if (k >= SIZE) return;

& arr[k++] = a;

}

int pop()

{

& if (k == 0)

& {

& cout << "Error! Stack is empty!\n";

& return 0;

& }

& k--;

& return arr[k];

}

};

struct Queue

{

int arr[SIZE];

int k;

Queue() : k(0) { }

void push(int a)

{

& if (k >= SIZE) return;

& for (int i = k; i >= 1; i--)

& {

& arr[i] = arr[i-1];

& }

& k++;

& arr[0] = a;

}

int pop()

{

& if (k == 0)

& {

& cout << "Error! Queue is empty!\n";

& return 0;

& }

& k--;

& return arr[k];

}

};

int main()

{

Stack s;

cout << "Stack: \n" ;

for (int i = 0; i < 10; i++)

{

& s.push(i+1);

}

for (int i = 0; i < 10; i++)

{

& cout << s.pop() << '\n' ;

}

Queue q;

cout << "Queue: \n";

for (int i = 0; i < 10; i++)

{

& q.push(i+1);

}

for (int i = 0; i < 10; i++)

{

& cout << q.pop() << '\n' ;

}

system("pause");

}

using namespace std;

const int SIZE = 10000;

struct Stack

{

int arr[SIZE];

int k;

Stack() : k(0) { }

void push(int a)

{

& if (k >= SIZE) return;

& arr[k++] = a;

}

int pop()

{

& if (k == 0)

& {

& cout << "Error! Stack is empty!\n";

& return 0;

& }

& k--;

& return arr[k];

}

};

struct Queue

{

int arr[SIZE];

int k;

Queue() : k(0) { }

void push(int a)

{

& if (k >= SIZE) return;

& for (int i = k; i >= 1; i--)

& {

& arr[i] = arr[i-1];

& }

& k++;

& arr[0] = a;

}

int pop()

{

& if (k == 0)

& {

& cout << "Error! Queue is empty!\n";

& return 0;

& }

& k--;

& return arr[k];

}

};

int main()

{

Stack s;

cout << "Stack: \n" ;

for (int i = 0; i < 10; i++)

{

& s.push(i+1);

}

for (int i = 0; i < 10; i++)

{

& cout << s.pop() << '\n' ;

}

Queue q;

cout << "Queue: \n";

for (int i = 0; i < 10; i++)

{

& q.push(i+1);

}

for (int i = 0; i < 10; i++)

{

& cout << q.pop() << '\n' ;

}

system("pause");

}

Learn more about our help with Assignments: C++

## Comments

## Leave a comment