Chains of Linked Nodes


Data Structures vs. ADTs

data structure =

 

 

 

abstract data type (ADT) =

 

 

 

 


Chain of Linked Nodes Data Structure

Conceptual picture:

 

 

Goal:

 

 

 


Java Visibility Modifiers

public    (public class ArrayList)

 

private    (private Object[] items)

 

protected    (protected String name)

 

________    (int studentID)

 

 


Listnode Class

class Listnode<E> { 
    private E data;
    private Listnode<E> next;
    
    public Listnode(E d) {
        this(d, null); 
    } 
    
    public Listnode(E d, Listnode<E> n) {
        data = d;
        next = n;
    } 
    
    public E getData() { return data; } 
    
    public Listnode<E> getNext() { return next; } 
    
    public void setData(E ob) { data = ob; } 
    
    public void setNext(Listnode<E> n) { next = n; } 
}

Practice with Chains of Linked Nodes

Making a chain of nodes

Create a chain of nodes containing the Strings "A", "B", and "C" (in that order) .

 

Traversing a chain of nodes

Assume head points to the first node in a chain of nodes containing Strings. Write a code fragment that counts the number of items in the chain of nodes.

 

Adding a node at the end of the chain

Assume head points to the first node in a chain of nodes containing Strings. Write a code fragment that adds "last" to the end of the chain of nodes. You may assume the chain has at least one item.

 

Removing a node from a chain

Assume head points to the first node in a chain of nodes containing Strings. Write a code fragment to remove the third item from the chain of nodes. You may assume the chain has at least three items.

 

Challenge

Assume head points to the first node in a chain of nodes containing Strings. Write a code fragment to reverse the chain of nodes.