Home > Blockchain >  Error converting decimal to binary using stack linked list [closed]
Error converting decimal to binary using stack linked list [closed]

Time:09-17

the goal of my program is to convert decimal to binary but when I run the code it shows the numbers that are pushed to the stack but suddenly after pushing the numbers the program crashed(exited) and doesn't show the return value of function 'conversion'.

#include<iostream>
#include<string>
using namespace std;

class Node{
    public:
        int data;
        Node *next;
        Node(){
            data = 0;
            next = NULL;
        }
};

class Stack{
    public: 
        Node *top;
    
        Stack(){
            top = NULL;
        }
};      

STACK FUNCTIONS

bool isEmpty(){
    Stack *top;
    return (top->top == NULL);
    }
    
void push(int n){
    Node *temp;
    temp = new Node;

    Stack *top;

    if(!temp){
        cout<<"Stack Overflow"<<endl;
        cout<<"Program terminated"<<endl;
        exit(1);
    }else{
        temp->data = n;
        temp->next = top->top;
        top->top = temp;
        cout<<n<<" :Pushed into stack."<<endl;
    }
}
    
void pop(){ 
    Node *temp;
    Stack *top;
    if(top->top == NULL){
        cout<<"Stack Underflow"<<endl;
        cout<<"Program terminated."<<endl;
        exit(1);
    }else{
        temp = top->top;    
        top->top = top->top->next;
        temp->next = NULL;
        delete temp;
    }   
}
    
    int peek(){
    Stack *top;
    if(isEmpty()){
        return top->top->data;
    }else{
        cout<<"Program terminated."<<endl;
        exit(1);
    }
}
    
void display(){
    cout<<"STORED STACK VALUES:"<<endl;
    Node *temp;
    Stack *top;

    if(top->top == NULL){
        cout<<"Stack Underflow"<<endl;
        cout<<"Program terminated."<<endl;
        exit(1);
    }else{
        while(temp != NULL){
            cout<<"Data: "<<temp->data<<endl;
            temp = temp->next;
        }
    }
}

LOGIC(converting decimal to binary)

string conversion(int x){
    while(x > 0){
        int rem = x % 2;
        push(rem);
        x = x/2;
   }    
    
    string bin_string = "";
    while(!isEmpty()){
        bin_string.append(to_string(peek()));
        pop();
    }

    cout<<"\nSTACK ARRAY APPROACH"<<endl;   
    return bin_string;
}

MAIN DRIVER

int main(){
    cout<<conversion(42)<<endl;

    return 0;
}

CodePudding user response:

In all of your Stack functions you just started to use an uninitailsed Stack* top; I think you wanted them to be the same, so you should

a) give them a top as a parameter

or

b) make Stack functions member functions of Stack and use this not an uninitalized top

  • Related