Stack using LL

Stack.h
#include "Singly LL.h"
#pragma once 

template<typename T>class Stack{
    SinglyLL<T> list;
public:
    bool isEmpty();
    bool isFull();
    void Push(const T val);
    bool Pop(T& val);
    T top();
};

template<typename T> T Stack<T> :: top() {
    SinglyLL<T> cur(list);
    T temp;
    cur.removeAtHead(temp);
    return temp;
}

template<typename T>bool Stack<T> :: isEmpty() {
    return list.Empty();
} 

template<typename T>bool Stack<T> :: isFull() {
    return false;
}

template<typename T>void Stack<T> :: Push (const T val) {
    list.insertAtHead(val);   
}

template<typename T>bool Stack<T> :: Pop (T& val) {
    if(isEmpty()) return false;
    
    list.removeAtHead(val);
    return true;
}
Singly LL.h
#include <iostream>
#pragma once
using namespace std;

template<typename T>class Node{
public:
	T data;
	Node* next;
	explicit Node(const T d) : data(d), next(nullptr) {}
};

template<typename T>class SinglyLL{
	Node<T>* head ;
	int elements;
public:
	SinglyLL(): elements(0), head(nullptr) {};

	SinglyLL(const SinglyLL<T>& list);
	
	void insert(const T val);
	
	void insertAtHead(const T val);
	
	bool remove(const T val);
	
	void removeAtHead(T& headData);

    bool Empty() { return elements == 0; }
};

template<typename T>SinglyLL<T> :: SinglyLL(const SinglyLL<T>& list) {
	Node<T>* listHead = list.head;
	Node<T>* newNode = new Node<T>(listHead -> data);
	Node<T>* cur = head = newNode;
	listHead = listHead -> next;

	while (listHead != nullptr) {
		Node<T>* temp = new Node<T>(listHead -> data);
		listHead = listHead -> next;
		cur -> next = temp;
		cur = temp;
	}
}

// Insert At Any Position
template<typename T>void SinglyLL<T> :: insert(const T val) {
	if(elements == 0) {
		Node<T>* newNode = new Node<T>(val);
		head = newNode;
		elements++;
		return;
	}
	
	Node<T>* newNode = new Node<T>(val);
	Node<T>* cur = head;
	
	while (cur -> next != nullptr) {
		cur = cur -> next;
	}
	cur -> next = newNode;
	elements++;
}

// Insert At Head
template<typename T>void SinglyLL<T> :: insertAtHead(const T val) {
	if(elements == 0) {
		Node<T>* newNode = new Node<T>(val);
		head = newNode;
		elements++;
		return;
	}
	
	Node<T>* newNode = new Node<T>(val);
	newNode -> next = head;
	head = newNode;
	elements++;
}

// Remove Head
template<typename T>void SinglyLL<T> :: removeAtHead(T& headData) {
	if(elements == 0) return ;

	if(elements == 1) {
		headData = head -> data;
		delete head;
		elements--;
		return ;
	}

	Node<T>* cur = head;
	headData = cur -> data;
	head = head -> next;
	delete cur;
	elements--;
	return;
}
main.cpp
#include "Stack.h"

int main()
{

    Stack<int> s1;
    s1.Push(1);
    s1.Push(2);
    s1.Push(3);
    s1.Push(4);

    cout << "Stack Top Element: " << s1.top() << endl;

    cout << "Stack Elements: ";
    while (!s1.isEmpty())
    {
        int temp;
        s1.Pop(temp);
        cout << temp << " ";
    }
    cout << endl;
}

Last updated

Was this helpful?