class IntSLLNode {
public:
int info;
IntSLLNode *next;
IntSLLNode(int el, IntSLLNode *ptr = 0) {
info = el; next = ptr;
}
};
class IntSLList {
public:
int length();
IntSLList() {
head = tail = 0; // or head = tail = NULL; NULL is equivalent to 0
}
~IntSLList();
int isEmpty() {
return head == 0;
}
void addToHead(int);
void addToTail(int);
int deleteFromHead();
int deleteFromTail();
void deleteNode(int);
bool isInList(int) const;
void printAll() const;
private:
IntSLLNode *head, *tail;
};
#include <iostream>
#include "List.h"
usingnamespace std;
/******addToHead******/
void IntSLList::addToHead(int el) {
head = new IntSLLNode(el,head);
if (tail == 0) //empty list
tail = head;
}
/******addToTail******/
void IntSLList::addToTail(int el) {
if (tail != 0) { // if list not empty;
tail->next = new IntSLLNode(el);
tail = tail->next;
}
else
head = tail = new IntSLLNode(el);
}
/******deleteFromHead******/
int IntSLList::deleteFromHead() {
int el = head->info; // causes crash if list empty
IntSLLNode *tmp = head;
if (head == tail) // if only one node on the list
head = tail = 0;
else
head = head->next;
delete tmp;
return el;
}
/******deleteFromTail******/
int IntSLList::deleteFromTail() {
int el = tail->info; // causes crash if list is empty
if (head == tail) { // if only one node on the list
delete head;
head = tail = 0;
}
else { // if more than one node in the list
IntSLLNode *tmp; // find the predecessor of tail
for (tmp = head; tmp->next != tail; tmp = tmp->next);
delete tail;
tail = tmp; // the predecessor of tail becomes tail
tail->next = 0;
}
return el;
}
/******deleteNode******/
void IntSLList::deleteNode(int el) {
if (head != 0) // if non-empty list;
{if (head == tail && el == head->info) { // if only one
delete head; // node on the list;
head = tail = 0;
}
elseif (el == head->info) { // if more than one node on the list
IntSLLNode *tmp = head;
head = head->next;
delete tmp; // and old head is deleted;
}
else { // if more than one node in the list
IntSLLNode *pred, *tmp;
for (pred = head, tmp = head->next; // and a non-head node
tmp != 0 && !(tmp->info == el);// is deleted;
pred = pred->next, tmp = tmp->next);
if (tmp != 0) {
pred->next = tmp->next;
if (tmp == tail)
tail = pred;
delete tmp;
}
}
}}
/******printAll******/
void IntSLList::printAll() const {
for (IntSLLNode *tmp = head; tmp != 0; tmp = tmp->next)
cout << tmp->info << " ";
cout << endl;
}
/******isInList******/
bool IntSLList::isInList(int el) const {
IntSLLNode *tmp;
for (tmp = head; tmp != 0 && !(tmp->info == el); tmp = tmp->next);
return tmp != 0;
}
/******destructor******/
IntSLList::~IntSLList() {
for (IntSLLNode *p; !isEmpty(); ) {
p = head->next;
delete head;
head = p;
}
}
/******Length******/
int len (IntSLList *ptr)
{
if (ptr!=0)
return len(ptr->next)+1;
elsereturn 0;
}
/*
int IntSLList::length(){
int count=0;
IntSLLNode* tmp;
for(tmp=head;tmp!=0;tmp=tmp->next)
count++;
return count;
}
*/
//here you should define len() function
//int IntSLList::length()
// len(head);