CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Collections

Collections and Generics
LinkedList class
Chain of nodes

A class Chain creates a chain of Node objects such that each Node holds a String entered via the console.

import java.util.*;

public class Chain
{
    private class Node 		// a class declared within Chain, an inner class
    {
		private String data;
		private Node next;

		public Node()    	// default constructor
		{
			data = "";
			next = null;
		}

		public Node(String s)	// one argument constructor
		{
			data = s;
			next = null;
		}

    }

	private Node front;	// holds the address of the first node of the chain

	public Chain()		// constructor builds a chain
	{
		Scanner input = new Scanner(System.in);
		String name;
		Node q, r;
		System.out.print("Enter name -- Press  to signal end of data: ");
		name = input.nextLine();

		// create the first node
		front = new Node(name);
		q = front; // front and q both reference the first node
		System.out.print("Enter name: ");
		name = input.nextLine();

		while (!name.equals(""))
		{
			r = new Node(name);	// get a new node
			q.next = r;			// link the previous node to the new node
			q = r;				// move q to the "new" node
			System.out.print("Enter name: ");
			name = input.nextLine();
		}
	}

	public void printChain()
	{
		Node q = front;		// q references the first node in the chain
		System.out.println("\nThe names in the chain of nodes are: ");
		while (q!=null)
		{
			System.out.println(q.data);
			q = q.next;		// move q to the next node in the chain
		}
	}

	public static void main(String[] args)
	{
		Chain chain = new Chain();
		chain.printChain();
	}
}
Previous | Class | Code | Chain of nodes | Stacks and Queues | Generic queue | ArrayList and LinkedList | Next