20-CS-122-001 Computer Science II Spring 2012
Array Implementation

Virtual functions, classes, inheritance, lists, queues, stacks, applications

Prev      Next      Lectures      list.0.cc

// An array can be used to implement a list
// But it is hard to add to or remove from or insert into an array 
// (unless it is the data structure within an abstract data type)
#include <iostream>
using namespace std;

int main () {
   int *lst = new int[10];
   int idx = 0;

   // add some elements to the end of the array
   lst[idx++] = 9;
   lst[idx++] = 4;
   lst[idx++] = 23;
   lst[idx++] = 2;

   // print the list
   for (int i=0 ; i < idx ; i++) cout << lst[i] << " ";
   cout << "\n";

   // find and remove the number 23 from the front
   int ptr = -1;
   for (int i=0 ; i < idx && ptr == -1 ; i++) if (lst[i] == 23) ptr = i;
   if (ptr >= 0) {
      for (int i=ptr ; i < idx-1 ; i++) lst[i] = lst[i+1];
      idx--;
   }

   // print the list
   for (int i=0 ; i < idx ; i++) cout << lst[i] << " ";
   cout << "\n";

   // Problems:
   //  1. user needs to keep track of size of list
   //  2. same code cannot be used for listing other objects
   //  3. same code, e.g. remove, gets repeated many times
   //  4. stuck with a fixed size array - may cause problems
}