单向链表C++
class IntSLLNode
{
public:
IntSLLNode()
{
next = 0;
}
IntSLLNode(int i, IntSLLNode *in = 0)
{
info = i;
next = in;
}
int info;
IntSLLNode *next;
private:
};
class IntSLList
{
public:
IntSLList()
{
head = tail = 0;
}
~IntSLList();
int isEmpty()
{
return head == 0;
}
void addToHead(int);
void addToTail(int);
int deleteFromHead();
int deleteFromTail();
void deleteNode(int);
bool isInList(int)const;
private:
IntSLLNode *head, *tail;
};
IntSLList::~IntSLList()
{
for (IntSLLNode *p; isEmpty();)
{
p = head->next;
delete head;
head = p;
}
}
void IntSLList::addToHead(int el)
{
head = new IntSLLNode(el, head);
if (tail == 0)
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 *temp = head;
if (head == tail)
{
head = tail = 0;
}
else
{
head = head->next;
}
delete temp;
return el;
}
int IntSLList::deleteFromTail()
{
int el = tail->info;
if (head == tail)
{
delete head;
head = tail = 0;
}
else
{
IntSLLNode *temp;
for (temp = head; temp->next != tail; temp = temp->next)
delete temp;
tail = temp;
tail->next = 0;
}
return el;
}
void IntSLList::deleteNode(int el)
{
if (head != 0)
if (head == tail && el == head->info)
{
delete head;
head = tail = 0;
}
else if (el==head->info)
{
IntSLLNode *temp = head;
head = head->next;
delete temp;
}
else
{
IntSLLNode *temp, *pred;
for (pred = head, temp = head->next; temp != 0 && !(temp->info == el); pred = pred->next, temp = temp->next);
if (temp != 0)
{
pred->next = temp->next;
if (temp->next)
tail = pred;
delete temp;
}
}
}
bool IntSLList::isInList(int el)const
{
IntSLLNode *temp;
for (temp = head; temp != 0 && !(temp->info = el); temp = temp->next)
return temp != 0;
}