stack.h
#pragma once
#include
using namespace std;
class Stack;
class Node{
int _data;
Node* _next;
Node(int data, Node* next);
friend class Stack;
};
class Stack{
Node* _top;
public:
Stack();
void push(int data);
int pop();
bool isEmpty();
int depth();
bool delNode(int num);
int append(int );
virtual ~Stack();
};
stack.cpp
#include "stack.h"
Node::Node(int data, Node* next){
_data = data;
_next = next;
}
Stack::Stack(){
_top = (Node*)0;
}
void Stack::push(int data){
Node* tempnode = new Node(data, _top);
_top = tempnode;
}
int Stack::pop(){
int ret = _top->_data;
Node* toDel = _top;
_top = _top->_next;
delete toDel;
return ret;
}
int Stack::depth(){
int ret=0;
Node* temp=_top;
while(temp){
ret += !!(temp);
temp=temp->_next;
}
return ret;
}
bool Stack:: delNode(int num){
int i;
bool done = false;
Node* cur =_top;
Node* prev = (Node*)0;
for(i=1; cur != (Node*)0 && !done && i<=num; i++){
if(i == num ){
Node* toDel= cur;
if(cur == _top){
pop();
done = true;
}
else {
prev->_next = cur->_next;
delete toDel;
done = true;
}
}
else {
prev = cur;
cur = cur->_next;
}
}
return done;
}
int Stack:: append(int data){
if(_top){
Node* temp = _top;
Node* Last = _top;
while(temp){
Last = temp;
temp = temp->_next;
}
Last->_next = new Node(data, (Node*)0);
}else
push(data);
return data;
}
bool Stack::isEmpty(){
return _top == (Node*)0;
}
Stack::~Stack(){
while(!isEmpty()) pop();
}
No comments:
Post a Comment