Код: Выделить всё
/*
Linked list goes from smallest to largest
*/
class List
{
public:
List():head(0), tail(0), theCount(0) {}
virtual ~List() {};
void insert(int value);
bool is_present(int value) const;
bool is_empty() const { return head == 0; }
void showAll();
int count() const {return theCount;}
private:
class ListCell
{
public:
ListCell(int value, ListCell* cell = 0):val(value), next(cell) {}
int val;
ListCell* next;
};
ListCell* head;
ListCell* tail;
int theCount;
};
insert:
Код: Выделить всё
void List::insert(int value) {
theCount++;
if (!head) {
/*
first insert sets the head and points to tail which is a nullPtr.
*/
head = new ListCell(value, 0);
//cout next = tail;
return;
}
else {
/*
Value smaller, therefore, we swap.
*/
tail = new ListCell(head->val, 0);
head->next = tail;
return;
}
}
ListCell* previousNode = head;
// the major problem, please advise me on the loop.
for (ListCell* nodePtr = head; nodePtr->next; nodePtr++) {
ListCell* next = nodePtr->next; // for convience
if (next == tail) {
if (value > next->val) {
// if the value is the largest in the list.
int oldVal = tail->val;
tail->val = value;
next = new ListCell(oldVal, tail);
previousNode = nodePtr;
break;
}
else {
// if the value is just before the tail.
next = new ListCell(value, tail);
previousNode = nodePtr;
break;
}
}
if (value < nodePtr->val) {
/*
if value is less than the node's value, then we create a nodePtr
*/
previousNode->next = new ListCell(value, nodePtr);
previousNode = nodePtr;
break;
}
previousNode = nodePtr;
}
}
Код: Выделить всё
int main() {
List mainList;
mainList.insert(10);
mainList.insert(12);
mainList.insert(15);
mainList.insert(11);
mainList.showAll(); // shows undefined values. probably indirecting empty pointers
return 0;
}
Подробнее здесь: https://stackoverflow.com/questions/784 ... etic-error