In: Computer Science
C++ coding functions
Implement the following class using linked
lists. Creating a simple linked list class to use is
probably your
first step.(Please do not use collections like .push() . pop(),
etc.) and instead create the implementation
A templated stack class that stores
type T with the following public functions:
- void Push(T t) - adds t to the top of the
stack
- T Pop() - asserts that the stack is not empty
then removes and returns the item at the top of the stack.
- T Peek() - asserts that the queue is not empty
then returns the item at the top of the stack without removing
it.
- unsigned int Size() - returns the number of items currently in the stack
#include<iostream>
using namespace std;
int c=0;
template<class T>
class node
{
public:
T data;
node<T>* next;
};
template <class T>
class Stack
{
private:
node<T>* top;
public:
Stack() {
top = NULL;
}
void push(const T & val) {
if (top == NULL) {
top = new node<T>;
top->next = NULL;
top->data = val;
}
else {
node<T>* temp = new node<T>;
temp->data = val;
temp->next = top;
top = temp;
}c++;
}
void pop()
{
if (top == NULL) {
cout << "Stack is empty" << endl;
return;
}
else {
cout << top->data << " is popped" <<
endl;
node<T>* temp = top;
top = top->next;
delete temp;
}
c--;
}
void print()
{
node<T>* temp = top;
if (top == NULL)
{
cout << "Stack is empty" << endl;
return;
}
else
{
while (temp != NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
}
}
int getsize()
{
return c;
}
};
int main()
{
Stack<int> s;
int choice;
while (1)
{
cout << "\n1. Push 2. Pop 3. Print 4.getsize 5. Quit"
<< endl;
cout<<" \nEnter your choice:";
cin >> choice;
switch (choice)
{
case 1:
cout << "\nEnter a number to push in Stack?";
int n;
cin >> n;
s.push(n);
break;
case 2:
s.pop();
break;
case 3:
s.print();
break;
case 4:cout<<"size="<<s.getsize();
break;
case 5:
cout << "Quitting program........." << endl;
return 1;
default:
cout << "Invalid choice!!" << endl;
break;
}
}
return 0;
}
output