|
ex5-9list.cpp - Example 5-9 Linked List - List Source file (ex5-9list.cpp) |
#include <iostream>
#include <cstdlib>
using namespace std;
#include "ex5-9list.h"
List::List()
{
top_ = 0;
}
List::~List()
{
Node* temp = top_;
while (temp != 0) {
top_ = top_ -> next_;
delete temp;
temp = top_;
}
}
void List::push(int item)
{
Node* temp = new Node(item,top_);
if (!temp) {
cerr << "Unable to allocate memory for a Node. Exiting ...\n";
exit(-1);
}
else {
top_ = temp;
}
}
int List::pop()
{
Node* temp = top_;
top_ = top_->next_;
int value = temp->data_;
delete temp;
return value;
}
int List::top() const
{
return top_ -> data_;
}
void List::print() const
{
Node* temp = top_;
while (temp != 0) {
cout << temp -> data_ << ' ';
temp = temp -> next_;
}
cout << endl;
}
Node* List::find(int item)
{
Node* temp = top_;
while (temp != 0) {
if (temp->data_ == item) return temp;
temp = temp -> next_;
}
return 0;
}
bool List::remove(int item)
{
if (!find(item)) {
cerr << item << " is not in the List\n";
return false;
}
Node* temp1 = top_;
Node* temp2;
if (top_->data_ == item) {
top_ = top_ -> next_;
delete temp1;
return true;
}
while (temp1->next_->data_ != item) {
temp2 = temp1;
temp1 = temp1 -> next_;
}
temp2 = temp1 -> next_;
temp1->next_ = temp2 -> next_;
delete temp2;
return true;
}
CIS27: Programming in C++ Instructor: Joe Bentley