Yes, and u can do something along the lines of:
PHP Code:// singly linked list
class Node {
public:
Node (int data = 0) : Data(data) {}
~Node () { if (pNext) delete pNext; pNext = 0; Data=0; }
Node * pNext;
int Data;
}
class List {
Node * m_pHead;
int m_count;
public:
List () : m_pHead(0) {}
~List () { if (m_pHead) delete m_pHead; m_pHead=0;m_count=0; }
bool Add(int dat) {
Node * pNew = new Node(dat);
if (pNew) {
m_pHead->pNext = pNew;
m_count++;
return true;
}
return false;
}
bool Remove (int dat) {
Node * pTemp = m_pHead;
Node * pDelete = 0;
// find it first
if (pTemp->Data == dat) {
pDelete = pTemp;
// disconect, delete, and reconnect
m_pHead = m_pHead->pNext;
pDelete->pNext = 0;
delete pDelete;
pDelete = 0;
m_count--;
return true;
}
while (pTemp->pNext) {
if (pTemp->pNext->pData == dat) {
m_count--;
pDelete = pTemp->pNext;
// disconnect and delete
pTemp->pNext = pDelete->pNext;
delete pDelete;
pDelete = 0;
return true;
}
return false;
}
Node * First () {
return m_pHead;
}
// Dont use this (BAD)
// cuz the list gets added to at the top, bottom, left, right,
// and everywhere!! so just use the first and iterate thru it
Node * Item (int index) {
int i = -1;
Node * pFound = m_pHead;
while (pFound) {
if (++i == index) {
return pFound;
}
}
return 0;
}
int Count () const {
return m_count;
}
};




:MoMad:
Reply With Quote