Processing math: 100%

2.Lists, Stacks, Queues§

A list is a finite, ordered sequence of data items.

Important concept: List elements have a position.

Notation: <a0,a1,,an1>

What operations should we implement?

List Implementation Concepts

Our list implementation will support the concept of a current position.

Operations will act relative to the current position.

<20,23 | 12,15>

List ADT (1)

// List class ADT. Generalize by using "Object" for the element type.
// An alternative would be to use Java Generics.
public interface List { // List class ADT
  // Remove all contents from the list, so it is once again empty
  public void clear();

  // Insert "it" at the current location
  // The client must ensure that the list's capacity is not exceeded
  public boolean insert(Object it);

  // Append "it" at the end of the list
  // The client must ensure that the list's capacity is not exceeded
  public boolean append(Object it);

  // Remove and return the current element
  public Object remove();

List ADT (2)

  // Set the current position to the start of the list
  public void moveToStart();

  // Set the current position to the end of the list
  public void moveToEnd();

  // Move the current position one step left, no change if already at beginning
  public void prev();

  // Move the current position one step right, no change if already at end
  public void next();

  // Return the number of elements in the list
  public int length();

List ADT (3)

  // Return the position of the current element
  public int currPos();

  // Set the current position to "pos"
  public boolean moveToPos(int pos);

  // Return true if current position is at end of the list
  public boolean isAtEnd();

  // Return the current element
  public Object getValue();
}

List ADT Examples

List: <12 | 32,15>

L.insert(99);

Result: <12 | 99,32,15>

Iterate through the whole list:

for (L.moveToStart(); !L.isAtEnd(); L.next()) {
  it = L.getValue();
  doSomething(it);
}

List Find Function

// Return true if k is in list L, false otherwise
static boolean find(List L, int k) {
  for (L.moveToStart(); !L.isAtEnd(); L.next())
    if (k == (Integer)L.getValue()) return true; // Found k
  return false;                                  // k not found
}

Array-Based List Class (1)

class AList implements List {
  private Object listArray[];             // Array holding list elements
  private static final int defaultSize = 10; // Default size
  private int maxSize;                    // Maximum size of list
  private int listSize;                   // Current # of list items
  private int curr;                       // Position of current element
  // Constructors
  // Create a new list object with maximum size "size"
  AList(int size) { 
    maxSize = size;
    listSize = curr = 0;
    listArray = new Object[size];         // Create listArray
  }
  // Create a list with the default capacity
  AList() { this(defaultSize); }          // Just call the other constructor

Array-Based List Insert

1 / 6 Settings
<<<>>>

Inserting an element at the head of an array-based list requires shifting all existing elements in the array by one position toward the tail.

Created with Raphaël 2.1.2
  • // Insert "it" at current position
  • public boolean insert(Object it) {
  • if (listSize >= maxSize) return false;
  • for (int i=listSize; i>curr; i--) // Shift elements up
  • listArray[i] = listArray[i-1]; // to make room
  • listArray[curr] = it;
  • listSize++; // Increment list size
  • return true;
  • }
Proficient Saving... Error Saving
Server Error
Resubmit

Linked List Position (1)

1 / 3 Settings
<<<>>>

Here is a graphical depiction for a linked list storing five integers. The value stored in a pointer variable is indicated by an arrow "pointing" to something. A NULL pointer is indicated graphically by a diagonal slash through a pointer variable's box. The vertical line between the nodes labeled 23 and 10 indicates the current position (immediately to the right of this line).

Created with Raphaël 2.1.2
20
23
10
Created with Raphaël 2.1.2
12
15
Proficient Saving... Error Saving
Server Error
Resubmit

Linked List Position (2)

1 / 7 Settings
<<<>>>

Another problem is that we have no link to get us to the preceding node (shown in yellow). So we have no easy way to update the yellow node's next pointer.

Created with Raphaël 2.1.2
20
23
10
Created with Raphaël 2.1.2
12
15
head
curr
tail
Proficient Saving... Error Saving
Server Error
Resubmit

Linked List Position (3)

Created with Raphaël 2.1.2
Created with Raphaël 2.1.2
null
null
head
curr
tail

Created with Raphaël 2.1.2
null
20
23
10
12
Created with Raphaël 2.1.2
15
null
head
curr
tail

Linked List Class (1)

1 / 7 Settings
<<<>>>

Let's look at the data members for class LList.

  • class LList implements List {
  • private Link head; // Pointer to list header
  • private Link tail; // Pointer to last element
  • private Link curr; // Access to current element
  • private int listSize; // Size of list
Proficient Saving... Error Saving
Server Error
Resubmit

Linked List Class (2)

1 / 5 Settings
<<<>>>

Now we look at the constructors for class LList.

  • // Constructors
  • LList(int size) { this(); } // Constructor -- Ignore size
  • LList() { clear(); }
  • // Remove all elements
  • public void clear() {
  • curr = tail = new Link(null); // Create trailer
  • head = new Link(tail); // Create header
  • listSize = 0;
  • }
Proficient Saving... Error Saving
Server Error
Resubmit

Insertion

1 / 9 Settings
<<<>>>

The linked list before insertion. 15 is the value to be inserted.

Created with Raphaël 2.1.2
  • // Insert "it" at current position
  • public boolean insert(Object it) {
  • curr.setNext(new Link(curr.element(), curr.next()));
  • curr.setElement(it);
  • if (tail == curr) tail = curr.next(); // New tail
  • listSize++;
  • return true;
  • }
null
35
23
Created with Raphaël 2.1.2
12
null
head
curr
tail
it
  1. 15
Proficient Saving... Error Saving
Server Error
Resubmit

Removal

1 / 7 Settings
<<<>>>

Now we look at the remove method.

Created with Raphaël 2.1.2
  • // Remove and return current element
  • public Object remove () throws NoSuchElementException {
  • if (curr == tail) // Nothing to remove
  • throw new NoSuchElementException("remove() in LList has current of " + curr + " and size of "
  • + listSize + " that is not a a valid element");
  • Object it = curr.element(); // Remember value
  • curr.setElement(curr.next().element()); // Pull forward the next element
  • if (curr.next() == tail) tail = curr; // Removed last, move tail
  • curr.setNext(curr.next().next()); // Point around unneeded link
  • listSize--; // Decrement element count
  • return it; // Return value
  • }
null
23
8
35
Created with Raphaël 2.1.2
10
null
head
curr
tail
Proficient Saving... Error Saving
Server Error
Resubmit

Prev

1 / 10 Settings
<<<>>>

Finally, we will look at how a few other methods work.

Created with Raphaël 2.1.2
null
23
8
35
Created with Raphaël 2.1.2
10
null
head
curr
tail
Proficient Saving... Error Saving
Server Error
Resubmit

Overhead

Comparison of Implementations

Space Comparison

"Break-even" point:

DE=n(P+E)

n=DEP+E

E: Space for data value.

P: Space for pointer.

D: Number of elements in array.

Space Example

Freelist

System new and garbage collection are slow.

1 / 7 Settings
<<<>>>

We will illustrate using a freelist by performing a series of list operations. Let's start from an empty singly linked list and a freelist variable pointing to null.

Created with Raphaël 2.1.2
Created with Raphaël 2.1.2
null
null
Created with Raphaël 2.1.2
null
head
curr
tail
freelist
Proficient Saving... Error Saving
Server Error
Resubmit

Doubly Linked Lists

Created with Raphaël 2.1.2
null
20
23
12
Created with Raphaël 2.1.2
15
null
head
curr
tail

Container Class Design Issues

Doubly Linked Node (1)

class Link {            // Doubly linked list node
  private Object e;     // Value for this node
  private Link n;       // Pointer to next node in list
  private Link p;       // Pointer to previous node

  // Constructors
  Link(Object it, Link inp, Link inn) { e = it;  p = inp; n = inn; }
  Link(Link inp, Link inn) { p = inp; n = inn; }

  // Get and set methods for the data members
  public Object element() { return e; }                     // Return the value
  public Object setElement(Object it) { return e = it; }    // Set element value
  public Link next() { return n; }                          // Return next link
  public Link setNext(Link nextval) { return n = nextval; } // Set next link
  public Link prev() { return p; }                          // Return prev link
  public Link setPrev(Link prevval) { return p = prevval; } // Set prev link
}

Doubly Linked Insert

1 / 10 Settings
<<<>>>

The linked list before insertion. 15 is the value to be inserted.

Created with Raphaël 2.1.2
  • public boolean insert(Object it) {
  • curr = new Link(it, curr.prev(), curr);
  • curr.prev().setNext(curr);
  • curr.next().setPrev(curr);
  • listSize++;
  • return true;
  • }
it
  1. 15
null
23
8
35
Created with Raphaël 2.1.2
10
null
head
curr
tail
Proficient Saving... Error Saving
Server Error
Resubmit

Doubly Linked Remove

1 / 9 Settings
<<<>>>

Now we will look at the remove method. Here is the linked list before we remove the node with value 8.

Created with Raphaël 2.1.2
  • public Object remove() {
  • if (curr == tail) return null; // Nothing to remove
  • Object it = curr.element(); // Remember value
  • curr.prev().setNext(curr.next()); // Remove from list
  • curr.next().setPrev(curr.prev());
  • curr = curr.next();
  • listSize--; // Decrement node count
  • return it; // Return value removed
  • }
null
23
8
Created with Raphaël 2.1.2
35
null
head
curr
tail
Proficient Saving... Error Saving
Server Error
Resubmit

Stacks

LIFO: Last In, First Out.

Restricted form of list: Insert and remove only at front of list.

Notation:

Stack ADT

public interface Stack { // Stack class ADT
  // Reinitialize the stack.
  public void clear();

  // Push "it" onto the top of the stack
  public boolean push(Object it);

  // Remove and return the element at the top of the stack
  public Object pop();

  // Return a copy of the top element
  public Object topValue();

  // Return the number of elements in the stack
  public int length();
}

Array-Based Stack (1)

Issues:

Array-Based Stack (2)

class AStack implements Stack {
  private Object stackArray[];    // Array holding stack
  private static final int defaultSize = 10;
  private int maxSize;            // Maximum size of stack
  private int top;                // First free position at top

  // Constructors
  AStack(int size) {
    maxSize = size;
    top = 0; 
    stackArray = new Object[size]; // Create stackArray
  }
  AStack() { this(defaultSize); }

Linked Stack

// Linked stack implementation
class LStack implements Stack {
  private Link top;               // Pointer to first element
  private int size;               // Number of elements

  // Constructors
  LStack() { top = null; size = 0; }
  LStack(int size) { top = null; size = 0; }

What are the costs of the operations?

How do space requirements compare to the array-based stack implementation?

Queues

FIFO: First in, First Out

Restricted form of list: Insert at one end, remove from the other.

Notation:

Queue Implementation (1)

1 / 5 Settings
<<<>>>

Assume that there are n elements in the queue. By analogy to the array-based list implementation, we could require that all elements of the queue be stored in the first $n$ positions of the array.

front
rear
  1. 4
listSize
  1. 120
  2. 451
  3. 52
  4. 813
  5. 4
  6. 5
  7. 6
  8. 7
Proficient Saving... Error Saving
Server Error
Resubmit

Queue Implementation (2)

1 / 9 Settings
<<<>>>

A more efficient implementation can be obtained by relaxing the requirement that all elements of the queue must be in the first $n$ positions of the array. We still require that the queue be stored be in contiguous array positions, but the contents of the queue will be permitted to drift within the array.

Proficient Saving... Error Saving
Server Error
Resubmit

Queue Implementation (3)

1 / 7 Settings
<<<>>>

This implementation raises a new problem. When elements are removed from the queue, the front index increases.

  1. 0
  2. 1
  3. 2
  4. 173
  5. 34
  6. 305
  7. 46
  8. 7
  9. 8
  10. 9
  1. 3
front
  1. 6
rear
  1. 4
listSize
Proficient Saving... Error Saving
Server Error
Resubmit

Circular Queue (1)

1 / 5 Settings
<<<>>>

The "drifting queue" problem can be solved by pretending that the array is circular and so allow the queue to continue directly from the highest-numbered position in the array to the lowest-numbered position.

Created with Raphaël 2.1.2
0
1
2
3
4
5
6
7
8
9
10
11
Proficient Saving... Error Saving
Server Error
Resubmit

Circular Queue (2)

1 / 8 Settings
<<<>>>

There remains one more serious, though subtle, problem to the array-based queue implementation. How can we recognize when the queue is empty or full?

Created with Raphaël 2.1.2
0
1
2
3
4
5
6
7
8
9
10
11
Proficient Saving... Error Saving
Server Error
Resubmit