Home Java Java-tips Data Collections Lists Simple Linked Lists

Ask Questions?

View Latest Questions


 
 

Simple Linked Lists
Posted on: July 26, 2006 at 12:00 AM
A simple singly-linked list. This shows the basics.

Java Notes: Simple Linked Lists

This shows three programs.

  • A simple singly-linked list. This shows the basics.
  • A doubly-linked list. This is almost as simple as the singly-linked list, but makes some operations easier.
  • Use of the java.util.LinkedList class, which is easy to use because it hides the details.

Simple singly-linked list done "by hand"

The following program is an example of a very simple implementation of a singly-linked list. You should become very comfortable with this. Altho you should always prefer the predefined java.util.LinkedList class when working with linked lists, understanding linking objects is essential to building other structures for which there is no predefined library class.

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
 36 
 37 
 38 
 39 
 40 
 41 
 42 
 43 
 44 
 45 
 46 
 47 
 48 
 49 
 50 
 51 
 52 
 53 
 54 
 55 
 56 
// Purpose: Demonstrates a really simple singly-linked list.
//          Main builds list of words, prints it using two styles.
// Author : Fred Swartz, 21 Feb 2006, placed in the public domain.

import java.util.Scanner;

public class SimpleSinglyLinkedList {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        
        Elem front = null;    // First element of list.
        Elem back  = null;    // Last element of list.
        
        //... Read a list of words.
        while (in.hasNext()) {
            String word = in.next();
            
            Elem e = new Elem();     // Create a new list element.
            e.data = word;           // Set the data field.
            
            //... Two cases must be handled differently
            if (front == null) {
                //... When the list is empty, we have to set the front pointer.
                front = e;            // Back element will be set below.
            } else {
                //... When we already have elements, we need