#ifndef _TEST_HPP_
#define _TEST_HPP_
class IntSLLNode
{
public:
IntSLLNode()
{
this->next = NULL;
}
IntSLLNode(int i, IntSLLNode *in = NULL)
{
this->info = i;
this->next = in;
}
int info;
IntSLLNode *next;
};
class IntSLList
{
public:
IntSLList()
{
head = tail = NULL;
}
~IntSLList();
int isEmpty()
{
return (head == NULL);
}
void addToHead(int);
void addToTail(int);
int deleteFromHead();
int deleteFromTail();
void deleteNode(int);
bool isInList(int) const;
private:
IntSLLNode *head, *tail;
};
#endif
#include <iostream>
#include "test.hpp"
using namespace std;
IntSLList::~IntSLList()
{
IntSLLNode *tmp = NULL;
while (! isEmpty())
{
tmp = head;
head = head->next;
delete tmp;
}
}
void IntSLList::addToHead(int e)
{
head = new IntSLLNode(e, head); // good to learn
if (tail == 0)
{
tail = head;
}
}
void IntSLList::addToTail(int e)
{
if (tail != 0)
{
tail->next = new IntSLLNode(e, NULL);
tail = tail->next;
}
else
{
head = tail = new IntSLLNode(e, NULL);
}
}
// ingore empty list
int IntSLList::deleteFromHead()
{
int el = head->info;
IntSLLNode *tmp = head;
if (head == tail)
{
head = tail = 0;
}
else
{
head = head->next;
}
delete tmp;
return el;
}
// ingore empty list
int IntSLList::deleteFromTail()
{
int el = tail->info;
if (head == tail)
{
delete tail;
head = tail = 0;
}
else
{
IntSLLNode *tmp = head;
for (; tmp->next != tail; tmp = tmp->next); // for can explain all kinds of loop
delete tail;
tail = tmp;
tail->next = NULL;
}
return el;
}
// ingore empty list
void IntSLList::deleteNode(int el)
{
if (head->info == el)
{
deleteFromHead();
}
else if (tail->info == el)
{
deleteFromTail();
}
else
{
for (IntSLLNode *pre = head; pre->next != tail; pre = pre->next)
{
if (pre->next->info == el)
{
IntSLLNode *node = pre->next;
pre->next = pre->next->next;
delete node;
}
}
}
}
bool IntSLList::isInList(int el) const
{
IntSLLNode *tmp = head;
for (; tmp != NULL; tmp = tmp->next)
{
if (tmp->info == el)
{
return true;
}
}
return false;
}
int main()
{
IntSLList list;
list.addToHead(10);
list.addToHead(20);
list.addToHead(30);
list.addToTail(0);
cout << list.deleteFromHead() << endl;
cout << list.deleteFromTail() << endl;
cout << list.isEmpty() << endl;
list.deleteNode(10);
list.isInList(20);
list.deleteNode(20);
return 0;
}
调试过程中犯的两个错误:
1、if分支“==”判断笔误写成了“=”,导致条件永远为真;
2、IntSLList::addToTail函数在插入节点时,原Tail指针未正确指向新增节点,导致新增节点孤立,进而遍历错误。