****************************IntSLList.h*****************************/
#ifndef _INTSLLIST_H_
#define _INTSLLIST_H_
class IntSLLNode{
public:
IntSLLNode(){next = 0;}
IntSLLNode(int el, IntSLLNode *ptr = 0){
info = el; next = ptr;
}
int info;
IntSLLNode *next;
};
class IntSLList{
public:
IntSLList(){head = tail = 0;}
~IntSLList();
int isEmpty(){return head == 0;}
void addToHead(int);
void addToTail(int);
void deleteNode(int);
bool isInList(int)const;
void print()const;
private:
IntSLLNode *head,*tail;
};
#endif
/**************************IntSLList.cpp****************************/
#include "IntSLList.h"
#include <iostream>
IntSLList::~IntSLList()
{
for(IntSLLNode *p; !isEmpty();){
p = head->next;
delete head;
head = p;
}
}
void IntSLList::addToHead(int el)
{
head = new IntSLLNode(el);
if(0 == tail)
tail = head;
}
void IntSLList::addToTail(int el)
{
if(tail != 0){
tail->next = new IntSLLNode(el);
tail = tail->next;
}
else{
head = tail = new IntSLLNode(el);
}
}
int IntSLList::deleteFromHead()
{
int el = head->info;
IntSLLNode *tmp = head;
if(head == tail)
head = tail = 0;
else
head = head->next;
delete tmp;
return el;
}
int IntSLList::deleteFromTail()
{
int el = tail->info;
if(head == tail){
delete head;
head = tail = 0;
}
else{
IntSLLNode *tmp;
for(tmp = head; tmp->next != tail; tmp = tmp->next);
delete tail;
tail = tmp;
tmp->next = 0;
}
return el;
}
void IntSLList::deleteNode(int el)
{
if(head != 0)
if(el == head->info && head == tail){
delete head;
head = tail = 0;
}
else if(el == head->info){
IntSLLNode *tmp;
head = head->next;
delete tmp;
}
else{
IntSLLNode *pred,*tmp;
for(pred = head, tmp = head->next;
tmp !=0 && !(tmp->info == el);
pred = pred->next, tmp = tmp->next);
if(tmp != 0){
pred->next = tmp->next;
if(tmp == tail)
tail = pred;
delete tmp;
}
}
}
bool IntSLList::isInList(int el)const
{
IntSLLNode *tmp;
for(tmp = head; tmp !=0 && tmp->info != el; tmp = tmp->next);
return tmp != 0;
}
void IntSLList::print()const
{
IntSLLNode *tmp;
for(tmp = head; tmp != 0; tmp = tmp->next){
std::cout << tmp->info << ' ';
}
std::cout << std::endl;
}