Professional Documents
Culture Documents
s MyCharListPtr {
lic:
. .
vate:
ruct ListNode
char item;
ListNode* next;
;
MyCharListPtr::MyCharListPtr(): Size(0)
{
MyCharListPtr::~MyCharListPtr()
{
while ( !empty() )
pop_front();
} Click to add text
class MyCharListPtr {
public:
. . .
private:
struct ListNode
{
char item;
ListNode* next;
};
Click to add
ListNode* getPointerToNode(int text
nodeNo);
int Size;
void MyCharListPtr::display()
{
cout << "[";
cur = head;
while (cur != NULL)
{
cout << cur->item;
cur = cur->next;
}
cout << "]" << endl;
}
Index operation :
ListNode* MyCharListPtr::getPointerToNode(int nodeNo) {
if ( empty() ) { cout << "Error : empty list" << endl; exit(1); }
if (nodeNo >= Size) { cout << "Error : past the end" << endl; exit(1); }
cur = head; int i = 0;
while (i < nodeNo) {
cur = cur->next;
i++; }
return cur;
}
char& MyCharListPtr::at(int nodeNo) {
ListNode* p = getPointerToNode(nodeNo);
return p->item;
}
char& MyCharListPtr::operator[](int nodeNo) {
ListNode* p = getPointerToNode(nodeNo);
return p->item;
}
Erasing a node :
void MyCharListPtr::erase(int nodeNo) {
if ( empty() ) {
cout << "Error : empty list" << endl;
exit(1);
}
if (nodeNo==0)
{
ListNode* oldhead = head;
head = head->next;
delete oldhead;
} else {
prev = getPointerToNode(nodeNo-1);
cur = prev->next;
prev->next = cur->next;
delete cur;
}
Size--;
}
inserting a node :
void MyCharListPtr::insert(int nodeNo, char ch) {
ListNode* slot = new ListNode;
slot->item = ch;
if (nodeNo==0) {
slot->next = head;
head = slot;
} else {
prev = getPointerToNode(nodeNo-1);
cur = prev->next;
prev->next = slot;
slot->next = cur;
if (cur == NULL)
tail = slot;
}
Size++;
}
Other functions :
void MyCharListPtr::pop_front() {
if ( empty() ) {
cout << "Error : pop empty list" << endl; exit(1); }
ListNode* oldhead = head;
head = head->next;
delete oldhead;
Size--;
}
void MyCharListPtr::pop_back() {
if ( empty() ) {
cout << "Error : pop empty list" << endl; exit(1); }
if ( Size == 1 ) pop_front();
prev = getPointerToNode(Size-2);
cur = prev->next;
delete cur;
prev->next = NULL;
tail = prev; Size--;
}
char& MyCharListPtr::front() {
if ( empty() ) {
cout << "Error : empty list in front()" << endl;
exit(1);
}
return head->item;
}
char& MyCharListPtr::back() {
if ( empty() ) {
cout << "Error : empty list in back()" << endl;
exit(1);
}
return tail->item;
}