Lecture Notes No.6:
            ADT, Linked List

Linked list in Java:

Two different problems:

Each of the nodes is an object: we build a data type (class) to model it:

class ListNode{

public int item;

public ListNode next;

};

ListNode l; /* declaration of a "reference to" a ListNode*/

ListNode l1 = new ListNode();

ListNode l2 = new ListNode();

ListNode l3 = new ListNode();

l1.item = 1;

l2.item = 2;

l3.item = 3;

To fill in the pointers between them and link them together:

l1.next = l2;

l2.next = l3;

l3.next = null;

Basic Operations on list nodes:

- define constructors for it:

ListNode (int obj)

{

item = obj;

next = null;

}

ListNode (int obj, ListNode n)

{

item = obj;

next = n;

}

Java will no longer allow "new ListNode()", unless we define a 0-arg constructor.

We can build the previous list by:

ListNode l1 = new ListNode (1, new ListNode(2, new ListNode(3)));

We can obtain the element on the position n in the list:

public ListNode ptrTo(int position)

{

if(position < 1) return null;

if(position == 1) return this;

if(next == null) return null;

return next.ptrTo(position-1);

}

Let's write two more methods, search, which looks for an element in the list and insertAt, which inserts an element into a given position.

public boolean search (int element)

{

ListNode curr = this;

while (curr!=null){

if(curr.item == element)return true;

curr = curr.next;

}

return false;

}

Does this always work? What happens in the following scenario?

ListNode lst1 = new ListNode (1, new ListNode(2));

lst1.next.next = lst1;

lst1.search(4);

How can we fix this problem?

public void insertAt(int position, int element)

{

if(position ==1){// what to do here?}

else if(position ==2)

next = new ListNode(element, next);

else

next.insertAt(position-1, element);

}

We can not insert (or delete) from the front of the list, because all we have is the "this" pointer to the first node.

Another problem: how can we represent an empty list? A simple answer would be that an empty list should be represented by null, e.g.:

ListNode anEmptyList = null;

What if we call:

anEmptyList.search(4);

anEmptyList.ptrTo(3);

Both calls would fail, because there is no object to receive those methods.

What can be done? Introduce a new data type List

class List{

private ListNode head;

public List(){head = null;}

public void insertFront (int obj)

{

head = new ListNode(onj, head);

}

// other methods to be declared

public boolean isEmpty(){...}

public Object removeFront() {...}

public Object removeBack(){...}

public void insertBack(Object value){...}

public ListNode nth(int i){...}

public void insertAfter(ListNode node, Object value){...}

}

public class ListNode{

public Object item;

public ListNode next;

public ListNode(Object value){item = value;}

}

(Rewrite the methods defined above for the new class List.)

Please notice that I changed the type of the item field from int to Object to be able to accomodate any type of data in this field.

Now I'm going to try to convince you that data structures should be encapsulated so they can be accessed only through well-defined interfaces. Data structures treated this way are called ABSTRACT DATA TYPES. If you don't do this way, you will bankrupt the company you work for. Data encapsulation makes a big difference to the number of bugs and the ease of maintenance of large software programs.

To motivate ADTs, listen a story about Doofie the Lazy Programmer. So, Doofie applies for a job as a linked list enginner at a Sunnyvale startup called CyberTrendy Webscapes Inc. Like all Silicon Valley startups, Cybertrendy is desperate for any flesh can hack, so they hire Doofie. Doofie, now a programmer at a Silicon VAlley startup implemented a linked list like the one I gave it to you above. He also wrote the code that uses linked lists. One day, Doofie needed to write code that would splice a node out of the middle of a list. It would only take a few lines, and he didn't foresee ever needing to use the splice operation anywhere else. Being lazy, Doofie didn't feel like adding a splice() method to the List class. Instead, he just did the work directly:

public class ListMangler {

[lotsa code]

ListNode node = list.nth(k);

/* Gosh, I am sooooooooooooooooooo tired. */

node.next = node.next.next;

[lotsa more code]

}

Two years later, CyberTrendy has fallen behind their competitor, Alta Lista, in the heated linked list market. In an effort to regain their former lead, they put crack programmer Genie Yess on the job. Genie decides to replace CyberTrendy's old lists with leading-edge doubly-linked technology. Two years later, another programmer, Genie Yess, decides to improve the speed of their list data structure. After careful thought, she decides to reprogram the List class so that it uses doubly-linked lists internally. A "previous" field is added to ListNode, and the List methods are rewritten.

public class List {

public ListNode head;

public List() {

head = new ListNode(null);

head.next = head;

head.previous = head;

}

[Same methods as before, rewritten.]

}

public class ListNode{

public Object item;

public ListNode next;

public ListNode previous;

public ListNode(Object value){

item = value;

}

}

Genie tests her new List implementation extensively, and can find no bugs. But when she replaces Doofie's List class with her own, the company's landmark ListMangler application repeatedly produces the wrong results. After six weeks of debugging, Genie discovers the culprit: Doofie's single line of splicing code. This kind of bug is one of the most difficult to find and fix. Unfortunately, Genie still has to debug 100,000 lines of Doofie's code in other failing applications, as well as 500,000 lines more written by other programmers who also directly manipulated the ListNode data structure.

Why doesn't she get Doofie to help her? Well, Doofie got offered $20,000 more to work for Alta Lista, and can't even speak to Genie for fear of being sued for giving away corporate trade secrets. CyberTrendy estimates the cost of having a team of programmers find and correct all of the code that illicitly modifies a ListNode. The List improvement project is abandoned.

The shocking example I just gave you is fictional, and it is taken from the JAVA class taught at Berkeley.

A remedy: Encapsulation

You encapsulate a data structure by defining an interface through which the outside world can inspect and manipulate it. The interface is the set of signatures and behavior of the methods that access the data structure (NOT the JAVA interface keyword we are going to talk about later in the lecture).

Think of an abstract data type as a closed box. Data can only go in and out through the interface. Other attempts to access the internals of the box are forbidden.

Signatures are the methods with their parameters and return values.

public ListNode ntf(int i)

Behavior guarantees about how the ADT behaves when its methods are invoked:

nth: return a reference to the ListNode at position i in the list.

Why encapsulation is your friend:

Teamwork.

The implementation is independent of the functionality.

Enforcing encapsulation

Most languages offer only one construct for enforcing the encapsulation of ADTs: self-discipline.

Obviously, Doofie's a bit short of that. Most programmers learn self-discipline through years of experience, shooting themselves in the foot over and over again with their own bugs, or having to fix other people's bugs. For really huge software products, encapsulation is critical to prevent the project from failing.

Fortunately, Java offers facilities that fortify your self-discipline. You're

already familiar with them. Most important is the ability to declare variables "private", "package" (default), or "protected". We can improve Doofie's List:

public class List {

private ListNode head;

public List() {

head = null;

}

}

public class ListItem ListNode{

Object item;

ListINode next;

ListNode (Object value){

item = value;

}

}

Every wonder why you would want to declare a private or package variable?

The answer: to stop the Doofies of the world (possibly including yourself) from messing with your data structures. In this example, List.head is private, so it can only be accessed within the List ADT. ListNode.item and ListNode.next are declared "package", so they can be accessed by the class List (List and ListNode are in the same package), but Doofie's evil scrawling, "node.next = node.next.next", is prohibited in outside applications.

Notice that we are still declaring the "ListNode" class "public". Strangely, this means that an application can declare and hold a ListNode reference, yet cannot access the data inside the ListNode! Sometimes this is very useful, as in the following application code:

ListNode kNode = currentList.nth(k); //find the k-th node

insertAfter(kNode, someObject); //insert Object at pos. k-1

Yet Doofie's evildoing is still impossible, because he can't access kNode.next.

Invariants

In some implementations of ADTs, there are invariants that obviously must hold unless the data structure is corrupted. For instance, in a doubly-linked list:

INVARIANT: If x and y are ListNodes, if x.next == y, then y.prev == x

When Genie tried replacing Doofie's List implementation with her own, Doofie's application code violated this invariant. An advantage of ADTs is that, if all of the methods in an ADT preserve the invariants, then the data structure can't be corrupted. How do you know whether all the methods preserve the invariants? Write a method that checks whether the data structure satisfies all its invariants, and prints an error message if it doesn't. Have all the other methods invoke this method when they're done their work.

public class List {

static final boolean listDebug = true;

...[lotsa code]...

private void validateList() {

[Check that the List is properly doubly-connected; report errors.]

}

public void insertAfter(ListNode node, Object value) {

[Insert a ListNode containing value after the ListNode "node".]

/* Now check if the data structure was corrupted. */

if (listDebug) {

validateList();

}

}

}

When you're sure all the bugs are out, set "listDebug" to false for more speed.

In some implementations of ADTs, there are invariants that obviously must hold unless the data structure is corrupted. For instance, in a doubly-linked list:

[1] head != null

[2] If x is a ListNode, then x.next != null, and x.previous != null

[3] If x and y are ListNodes, and x.next == y, then y.previous == x

[4] If x and y are ListNodes, and x.previous == y, then y.next == x

When Genie tried replacing Doofie's List implementation with her own, Doofie's application code violated Invariants [3] and [4]. An advantage of ADTs is that, if all of the methods in an ADT preserve the invariants, then the data

structure can't be corrupted.

A double linked list:

class DoubleListNode{

Object item;

DoubleListNode previous;

DoubleListNode next;

}

class DoubleList{

DoubleListNode head;

//other constructors and methods

}

Here are some important facts about invariants:

[1] ADT invariants don't have to be true while a method of the ADT is executing; they only have to be true when the method is finished.

[2] You may assume that the data structure is in a legal state whenever a method is called.

[3] It is sometimes possible to PROVE that, if your method is passed a data structure that satisfies the invariants, it will return a correctly modified data structure that satisfies the invariants.

[4] We will deduct points from your future homeworks and projects if you declare fields "public" when they should be "private" or "protected". When is it okay to declare a field "public"? When an external programmer's meddling _cannot_ cause an invariant to be violated. (Even so, leave a field "private" if it's not inconvenient for you.)

[5] When you implement an ADT, always write down the invariants in your comments. (Sometimes it's hard to think of them all, but do your best.) They can help you debug: check each method, and make sure you believe that it's preserving each invariant.

[6] If you're stumped by bugs, try this aggressive debugging technique: Write a method that checks whether your data structure satisfies all its invariants, and prints an error message if it doesn't. Have all the other methods invoke this method just before they return.