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

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

Prev      Next      Lectures      list.1.cc      power point demo

// 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)
//
// Attempt at solving these problems:
//  1. repeated sections of code
//  2. have to worry about the size of the array

#include <iostream>
using namespace std;

int list_size = 0;

void show (int *lst) {
   if (lst == NULL) cout << "(empty)";
   else
      for (int i=0 ; i < list_size ; i++) cout << lst[i] << " ";
   cout << "\n";
}

void add (int **lst, int item) {
   int *tmp = new int[list_size+1];
   for (int i=0 ; i < list_size ; i++) tmp[i] = (*lst)[i]; 
   tmp[list_size++] = item;
   *lst = tmp;
}

void remove (int **lst, int item) {
   if (list_size <= 1) {
      list_size = 0;
      *lst = NULL;
      return;
   }
   int ptr = -1;
   int *tmp = new int[list_size-1];
   for (int i=0; i= 0) {
      for (int i=0 ; i < ptr ; i++) tmp[i] = (*lst)[i];
      for (int i=ptr ; i < list_size-1 ; i++) tmp[i] = (*lst)[i+1];
      delete *lst;
      *lst = tmp;
      list_size--;
   }
}

int main () {
   int *lst = NULL;
   show(lst);

   // add some elements to the end of the array
   add(&lst, 9);
   add(&lst, 4);
   add(&lst, 23);
   add(&lst, 2);
   show(lst);

   // remove an element from the front
   remove(&lst, 23);
   show(lst);

   // Problems:
   //  1. same code cannot be used for listing other objects
   //  2. code for add, remove does not look so hot
   //  3. what's with the & and **?
   //  4. always asking for memory from OS when add and remove invoked
}