life4
life4

Reputation: 75

Printing stack with linked list without struct

I'm trying to create a stack using linked lists in c++ without struct.Bot i can't wirte display function how can i display ?Any help or clarification is much appreciated. Thanks

    class StackNode { 
public: 
    int data; 
    StackNode* next; 
}; 

StackNode* newNode(int data) 
{ 
    StackNode* stackNode = new StackNode(); 
    stackNode->data = data; 
    stackNode->next = NULL; 
    return stackNode; 
} 

int isEmpty(StackNode* root) 
{ 
    return !root; 
} 

void push(StackNode** root, int data) 
{ 
    StackNode* stackNode = newNode(data); 
    stackNode->next = *root; 
    *root = stackNode; 
    cout << data << " pushed to stack\n"; 
} 


int peek(StackNode* root) 
{ 
    if (isEmpty(root)) 
        return INT_MIN; 
    return root->data; 
} 


Upvotes: 0

Views: 93

Answers (1)

Milan
Milan

Reputation: 88

You can print the data and move to the next node, till you reach the last node.

Code (Prints the stack, top to bottom):

void display(StackNode* root) 
{ 
    while(root!=NULL)
    {
      cout<<root->data<<'\n';
      root=root->next;
    }
}

Upvotes: 2

Related Questions