Linked list operations: insert
void insert(int value, int position) {
assert(position <= length());
// Insert at beginning (special case)
if (position == 0) {
ListNode * old_head = head;
head = new ListNode(value, NULL);
head->next = old_head;
} else {
ListNode * cursor = head;
// Loop down linked list
while (cursor != NULL) {
// Reached point to insert
if (1 >= position) {
ListNode * old_next = cursor->next;
cursor->next = new ListNode(value, NULL);
cursor->next->next = old_next;
break;
}
position--;
cursor = cursor->next;
}
}
}
Last modified: Thu Jul 13 13:44:32 PDT 2000