Sunday, October 14, 2012

Implementing Stack in C++ using Class Template


#include<iostream>
using namespace std;

template<class T>
class stack{
T* arr;
static int top;
public:
stack(int);
void push(T);
T pop();
bool empty();
};

template<class T>
int stack<T>::top = -1;

template<class T>
stack<T>::stack(int x){
this->arr = new T(x);
}

template<class T>
void stack<T>::push(T a){
this->arr[++top] = a;
}

template<class T>
T stack<T>::pop(){
T a = this->arr[top--];
return a;
}

template<class T>
bool stack<T>::empty(){
return (top==-1);
}

int main(){
stack<int> s(10);
int i;
for(i=0;i<10;i++){
s.push(i);
}
while(!s.empty()){
cout<<s.pop()<<endl;
}
return 0;
}

2 comments:

  1. #include
    #include
    using namespace std;
    template
    struct Stack {
    T *data;
    Stack* next;
    };
    // Creating node consisting of int elements
    template
    void createStack(Stack **stack, T *data,int n) {
    for(int i = 0; i < n; i++) {
    Stack *node = (Stack *)malloc(sizeof(Stack));
    node->data = &data[i];
    node->next = *stack;
    *stack = node;
    }
    }

    //Function to Print Stack
    template
    void printStack(Stack **stack) {
    if(stack == NULL || *stack == NULL)
    return;
    Stack *start = *stack;
    while(start != NULL) {
    printf("%c ",*(char *)start->data);
    start = (start)->next;
    }
    printf("\n");
    }

    // Function to push value at the top of stack
    template
    bool push(Stack **stack,T *data){
    Stack *head = *stack;
    Stack *node = (Stack *)malloc(sizeof(Stack));
    node->data = data;
    node->next = head;
    *stack = node;
    return true;
    }
    template
    bool pop(Stack **stack, T **data){
    if(stack == NULL || *stack == NULL ){
    return false;
    }
    else {
    Stack *head = *stack;
    Stack *node = head;
    *data = head->data;
    head = head->next;
    *stack = head;
    free (node);
    return true;
    }
    }

    // Function to delete the whole stack and free memory
    template
    void deleteStack(Stack **stack) {
    if(stack == NULL)
    return;
    Stack *start = *stack;
    while (*stack != NULL)
    {
    Stack *node = *stack;
    *stack = (*stack)->next;
    free (node);
    }
    }

    int main() {
    Stack* stack = NULL;
    char arr[10] = {'1','2','3','4','5','6'}; //Array to create initial stack
    createStack(&stack,arr,6); //create stack using values in array
    printStack(&stack); // Printing stack
    char i = '7';
    push(&stack,&i); // Push 7 at the top of stack O(1)
    printStack(&stack); //Print new stack
    char *data;
    if(pop(&stack,&data)==true); //Pop top element O(1)
    printf("Popped %c\n",*(char *)data);
    printStack(&stack); //Print stack after pop
    deleteStack(&stack); // Delete the stack and free memory
    printStack(&stack); //Print stack after delete
    return 0;

    }

    ReplyDelete