CPSC 221

The List ADT

Today

Announcements

  • PA1 is due Monday Oct 5 — this lecture is the preparation for it
  • Examlet 2 closes this weekend
  • Lab 3 this week


Where we’re going

  • The List ADT — what a user sees
  • An implementation — what we see
  • insert at position \(k\), with and without a sentinel
  • removeCurrent, twice

Abstract Data Type:

template<class LIT>
class List {
public:
    List();  // ~List(); ??
    int getSize() const;
    void insert(int loc, LIT e);
    void remove(int loc);
    LIT const & getItem(int loc) const;
private:
    // my little secret.
};
int main() {
    List<int> myList;
    myList.insert(1, 4);
    myList.insert(1, 6);
    myList.insert(2, 0);
    myList.insert(3, myList.getItem(2));
    cout << myList.getSize() << endl;
    myList.remove(2);
    cout << myList.getItem(3) << endl;
}

ADT List, an implementation:

template<class LIT>
class List {
public:
    List() : size(0), head(nullptr);
    ~List();  // + op= and cctor
    int getSize() const;
    void insert(int loc, LIT e);
    void remove(int loc);
    LIT const & getItem(int loc) const;
private:
    struct Node {
        LIT data;
        Node * next;
        Node(LIT newData) : data(newData), next(nullptr) { }
    };
    Node * head;
    int size;
};
template<class LIT>
Node * List<LIT>::Find(Node * place, int k) {
    if ((k == 0) || (place == nullptr))
        return place;

}


Find is private. Why?

Insert new node in \(k\)th position:

head 3 6 4
void List<LIT>::insert(int loc, LIT e) {




}

Analysis:        aside: insert new \(k\)th in an array:

Insert \(k\)th with a sentinel:

head 3 6 4
void List<LIT>::insert(int loc, LIT e) {
    Node * curr = Find(head, loc-1);
    Node * newN = new Node(e);
    newN->next = curr->next;
    curr->next = newN;
}

Wow, this is convenient! How do we make it happen?

template<class LIT>
List<LIT>::List() {



}

Remove node in a fixed position:

Given a pointer to the node you wish to remove.

head 4 2 7 8 curr

Solution #1:

void removeCurrent(Node * head, Node * curr) {



}

Analysis:

Remove node in a fixed position:

Constant time hack:

head 4 2 7 8 curr
void removeCurrent(Node * head, Node * curr) {



}