// Linked
list hints for CDLinks, assignment #7.
// Creates a
list of Nodes, implemented as a linked list.
Node could be called CD.
The main
program can be identical to CDstore2.java, as follows. What is different is the code that enables
us to make a linked list of the CD's, instead of an array:
class
CDLinks
{
public static void main (String []
args)
{
CDlist
cdlist = new CDlist ();
cdlist.readData
();
cdlist.addCD
();
cdlist.displayData
();
cdlist.storeData
();
} // method main
} // class
CDLinks
This might
be some class CD, or, as you may call it, class Node (the name doesn't
matter. It is the thing, with data
fields and a next field of its own type, which will get linked into the linked
list in class CDlist below):
class Node
{
private String name, artist,
company, catalog;
private int orderNo = 1;
private Node next;
Constructor
will include:
Node (String
n, String a, String comp, String cat,
int orderNo)
assign all the data fields.
also set next equal to null.
Other
methods for Node (or CD if you call it that):
public Node
getNext()
public void
setNext(Node next)
public void
readCDData (BufferedReader infile, String n)
throws IOException
identical to array version
public void
displayCD ()
identical to array version
public void
storeCD (PrintStream outfile)
identical to array version
} // end
class Node
// CDList,
where a lot more of the pointer stuff is needed. Some clues:
// It's like
the array version is some ways, with creating of newNode where
//
appropriate...
class CDlist
{
private Node listHead = null;
These
methods will be needed:
// Here is the code for a generic
addNode, as in the linked list program online and in class:
public void addNode ( Node newNode )
{
if
(listHead == null)
{
listHead = newNode;
newNode.setNext(null);
}
else
// list not empty
{
Node tempPtr = listHead;
while ( tempPtr.getNext() != null )
tempPtr
= tempPtr.getNext();
tempPtr.setNext( newNode );
}
} // addNode
// Please trace
displayData and addNode on paper to understand it.
// This will
enable you to understand how one moves around in a linked list.
public void
displayData()
{
Node
tempPtr = listHead;
while
(tempPtr != null)
{
tempPtr.displayCD();
tempPtr = tempPtr.getNext();
}
System.out.println
();
} // displayData
// Here are
a few more things:
BufferedReader
stdin = new BufferedReader (new InputStreamReader
(System.in));
public void
readData ()
You'll need this in the method:
// Get a
Node object for the CD
Node
newCDnode = new Node();
// Read
the data into the object
newCDnode.readCDData
(infile, name);
// Call
the method in Node to add it to the linked list
addNode
(newCDnode); replaces list[i].addNode();
public void
addCD ()
You'll need this in this method:
//
Get a Node object, using the constructor that assigns the data from the
parameters:
Node
newCDnode = new Node (name, artist, company, catalog, orderNo);
//
Add the object to the linked list:
addNode
(newCDnode);
public void
storeData ()
} // class
CDlist