[   ^ to index...   |   <-- previous   |   next -->   ]

Operations on linked lists

LinkedList::LinkedList() { head = NULL: } bool LinkedList::isEmpty() { return head == NULL: } int LinkedList::length() { ListNode * cursor = head; int count = 0; while (cursor != NULL) { cursor = cursor->next; count++; } return count; } void insert(int value, int position) { assert(position <= length()); if (position == 0) { // Insert at beginning ListNode * old_head = head; head = new ListNode(value); head->next = old_head; } else { ListNode * cursor = head; while (cursor != NULL) { // Loop down linked list // If we have reached point to insert if (1 >= position) { ListNode * old_next = cursor->next; cursor->next = new ListNode(value); cursor->next->next = old_next; break; } position--; cursor = cursor->next; } } }

Last modified: Thu Jul 13 13:37:00 PDT 2000