Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Table Doubling Program with Stack implementation //
- #include <iostream>
- using namespace std;
- typedef struct{
- int *arr;
- int top;
- int size;
- }stack;
- void push(stack* sp,int num){
- if(sp->top == sp->size-1){
- int *temp;
- //double the size//
- temp = (int*)malloc(sizeof(int)*sp->size*2);
- if(temp == NULL){
- cout << "failed to allocate";
- return;
- }
- for(int i=0; i <= sp->top ;i++){
- temp[i] = sp->arr[i];
- }
- free(sp->arr);
- sp->arr = temp;
- sp->size *=2;
- }
- sp->top++;
- sp->arr[sp->top] = num;
- return;
- }
- int pop(stack* sp){
- if(sp->top == -1){
- cout << "Stack Empty\n";
- return -99;
- }
- int num = sp->arr[sp->top];
- sp->top--;
- return num;
- }
- void freemem(stack* sp){
- if(sp->arr != NULL){
- free(sp->arr);
- sp->top = -1;
- sp-> size = 0;
- }
- }
- void print(stack* sp){
- cout << "Size of Stack: " << sp->size << "\n\n";
- if(sp->top == -1){
- cout << "stack empty\n\n";
- return;
- }
- for (int i=0;i<= sp->top ;i++){
- cout << sp->arr[i] << "\t";
- }
- cout << "\n\n";
- }
- void __init__(stack* sp,int size){
- sp->top = -1;
- sp->arr = (int*)malloc(sizeof(int)*size);
- if(sp->arr == NULL){
- cout << "cant make allocations\n\n";
- return;
- }
- sp->size = size;
- return;
- }
- int main(){
- stack s1;
- __init__(&s1,5);
- int choice,num;
- while(1){
- cout << "1: push 2: pop 3: print 4: exit" <<endl;
- cin >> choice;
- switch(choice){
- case 1:
- cout << "num: ";
- cin >> num;
- push(&s1,num);
- break;
- case 2:
- num = pop(&s1);
- cout << num <<endl;
- break;
- case 3:
- print(&s1);
- break;
- case 4:
- freemem(&s1);
- exit(0);
- default:
- cout << "Invalid choice\n\n";
- }
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment