LISTS

Like bags, lists are container classes. Unlike bags, order is important. List operations include: There are many varieties (interfaces) of lists.

Lists are extremely useful:

Implementations vary - depend on intended use.

We have and will look at lists throughout the semester. You can view the documentation and implementation of the StringList class implemented with arrays in string-list.h and string-list.C.

Lists are like Bags... they have similar interfaces: insert, isEmpty, etc. The same basic implementation can be used (for example, arrays), but they are NOT the same. Lists have no grab (although they could). Bags have no order. List insert is substantially different, since order must be preserved:

List::insert(int entry)
{
  assert(!isFull());

  for(size_t i=used; i > 0; i--)
    data[i] = data[i-1];
  data[0] = s;
  used++;
}

The state of lists

Lists need not just store data in order. They can also keep track of where in the data are we looking. This can be accomplished by maintaining a cursor. (Your cursor in your screen indicates where you are in a window; a cursor in a list indicates at which item you are in the list.) Operations to support the cursor include:

What are list cursors good for?

Not all list operations involve the cursor. Does "insert at front of the list" involve the cursor? Maybe. To fully specify our list interface, we need to indicate what happens to the cursor at each operation. Our goal is to avoid ambiguity.

Consider the following insertion into a list of integers:

3 7
^

   insert(4);


4 3 7          // cursor still points to same item
  ^
But what happens when we insert an item onto the empty list:
_
^             // cursor points to end

   insert(4);

4 
  ^           // cursor still points to end

              // OR

4
^             // cursor now points to first item
We need to choose. We specify in the postcondition: If the list was empty, the cursor is now at the front of the list (i.e. the first item). Otherwise, the cursor is unchanged.

You can read the specification of the remaining list functions in string-list.h.

Some examples of the use of the cursor:

3 4 7 
  ^

    remove();  // remove the item currently pointed to

3 7            // isEnd() is false
  ^

    remove();

3              // isEnd() is true
  ^

    remove();

???            // precondition violated!



_              // the empty list: 
^              //   isEmpty, isEnd, isFront all true

    insert(1);

1              // isFront() is true
^

    addAfterCurrent(5);

1 5
^

    addBeforeCurrent(7);

7 1 5
  ^

    advance();

7 1 5
    ^

    addAfterCurrent(3);

7 1 5 3
    ^
For the implementation of cursors and the rest of the List member functions using arrays see string-list.C.