--- In [email protected], John Gaughan <[EMAIL PROTECTED]> wrote:
>
> tatoy_roberto_bscs wrote:
> > asking for help about class in c++
> > about node with setters and getters and in Stack and Queue
> > in array impl. and in linked list implementation.
> > help!!!!!!!!!
> >
>
> What is your question?
>
> --
> John Gaughan
>
Hey. bart_pengyou here. I'm in a hurry that's why I only have Stack
here. For the array implementation, I think we have to know whether
the Stack and Queue are resizable. Anyway, here are codes for the
linked list implementation of stack. Note: my stack do have header
nodes!
/*Node.h*/
#ifndef NODE_H
#define NODE_H
class Node{
private:
int item;
Node *next;
public:
Node(){}
Node(int data, Node *ptr = NULL){ // constructor with default
argument for pointer field
item = data;
next = ptr;
}
int getItem() const{
return item;
}
Node *getNext() const{
return next;
}
void setItem(int data){
item = data;
}
void setNext(Node *ptr){
next = ptr;
}
};
#endif
/*Stack.h*/
#ifndef STACK_H
#define STACK_H
#include "Node.h"
class Stack{
private:
Node *head;
public:
Stack();
~Stack();
void clear();
void push(int data);
int pop(); //should not be called when stack is
empty
int peek(); //returns item at the top of stack
bool isEmpty() const;
};
#endif
/*Stack.cpp*/
#include <iostream.h>
#include "Stack.h"
Stack::Stack(){
head = new Node(0, NULL);
}
Stack::~Stack(){
clear();
delete head;
head = NULL;
}
void Stack::clear(){
Node *p = head->getNext();
while(p != NULL){
head->setNext(p->getNext());
delete p;
p = head->getNext();
}
}
void Stack::push(int data){
Node *newNode = new Node(data, head->getNext());
head->setNext(newNode);
}
int Stack::pop(){
Node *p = head->getNext();
int retVal = p->getItem();
head->setNext(p->getNext());
delete p;
return retVal;
}
int Stack::peek(){
return head->getNext()->getItem();
}
bool Stack::isEmpty() const{
return head->getNext() == NULL ? true : false;
}