| CCS 2100 | | Comp 310 | | CCS 1300 | | CCS 1200 | | CCS 1100 | | CCS 1000 | | CS 212 | | Email: cpuccs@yahoo.com

Monday, January 14, 2013

Linked Lists Example

The following is the link for the complete sample program of an integer list that use Link lists data structure. (Note: click the smaller download link, not the big one in the ads):

Linked Lists
http://www.2shared.com/file/wXvYA1aw/Linked.html

The file is in ZIP format. Simply extract it to access the codes.

Or you may encode the following 5 java classes:

---------------------------------TestProg_Linked.java-----------------------

import java.io.*;
import java.util.*;

public class TestProg_Linked
{
    static BufferedReader keyboard = new
           BufferedReader(new InputStreamReader(System.in));


    public static void main(String[] args) throws IOException
    {
        UnorderedLinkedList list
                          = new UnorderedLinkedList();

        IntElement num = new IntElement();
        StringTokenizer tokenizer;

        System.out.println("Enter integers ending with -999 on one line.");
        tokenizer = new StringTokenizer(keyboard.readLine());
        num.setNum(Integer.parseInt(tokenizer.nextToken()));

        while(num.getNum() != -999)
        {
            list.insertLast(num);
            num.setNum(
                Integer.parseInt(tokenizer.nextToken()));
        }

        System.out.println();

        System.out.println("list: ");
        list.print();
        System.out.println();
        System.out.println("Length of list: " + list.length());


        System.out.print("Enter the number to be deleted: ");
        System.out.flush();
        num.setNum(Integer.parseInt(keyboard.readLine()));

            //deleteNode
        list.deleteAll(num);

        System.out.println("After deleting all occurences of " + num + " list: ");
        list.print();
        System.out.println();

        System.out.println("Length of list: " + list.length());

        list.deleteSmallest();

        System.out.println("After deleting the smallest element, list:");

        list.print();
        System.out.println();

        System.out.println("Length of list: " + list.length());
    }
}
---------------------------------end of TestProg_Linked.java-----------------------

--------------------------DataElement.java---------------------------------------


public abstract class DataElement
{
    public abstract boolean equals(DataElement otherElement);
      //Method to determine whether two objects contain the 
      //same data.
      //Postcondition: Returns true if this object contains the 
      //               same data as the object otherElement;
      //               otherwise, it returns false.
      
    public abstract int compareTo(DataElement otherElement);
      //Method to compare two objects.
      //Postcondition: Returns a value < 0 if this object is 
      //                    less than the object otherElement;
      //               Returns 0 if this object is the same as 
      //                    the object otherElement.
      //               Returns a value > 0 if this object is 
      //                  greater than the object otherElement.
      
    public abstract void makeCopy(DataElement otherElement);
      //Method to copy otherElement into this object.
      //Postcondition: The data of otherElement is copied into
      //               this object.
      
    public abstract DataElement getCopy();
      //Method to return a copy of this object.
      //Postcondition: A copy of this object is created and
      //               a reference of the copy is returned.
}
----------------------end of DataElement.java--------------------------------

----------------------IntElement.java------------------------------------------------

public class IntElement extends DataElement
{
    protected int num;

      //default constructor
    public IntElement()
    {
        num = 0;
    }

      //constructor with a parameter
    public IntElement(int x)
    {
        num = x;
    }
      //copy constructor
    public IntElement(IntElement otherElement)
    {
        num = otherElement.num;
    }

      //Method to set the value of the instance variable num.
      //Postcondition: num = x;
    public void setNum(int x)
    {
        num = x;
    }

      //Method to return the value of the instance variable num.
      //Postcondition: The value of num is returned.
    public int getNum()
    {
        return num;
    }

    public boolean equals(DataElement otherElement)
    {
        IntElement temp = (IntElement) otherElement;
        return (num == temp.num);
    }

    public int compareTo(DataElement otherElement)
    {
        IntElement temp = (IntElement) otherElement;
        return (num - temp.num);
    }

    public void makeCopy(DataElement otherElement)
    {
        IntElement temp = (IntElement) otherElement;
        num = temp.num;
    }

    public DataElement getCopy()
    {
        IntElement temp = new IntElement(num);
        return temp;
    }

    public String toString()
    {
        return String.valueOf(num);
    }
}
----------------------end of IntElement.java-------------------------------------

---------------------LinkedListClass.java-------------------------------------------


public abstract class LinkedListClass
{
    protected class LinkedListNode
    {
        DataElement info;
        LinkedListNode link;
    }

    protected LinkedListNode first; //variable to store the
                                    //address of the first
                                    //node of the list
    protected LinkedListNode last;  //variable to store the
                                    //address of the last
                                    //node of the list
    protected int count;  //variable to store the number of nodes
                          //in the list


        //default constructor
        //Initializes the list to an empty state.
        //Postcondition: first = null, last = null,
        //               count = 0
    public LinkedListClass()
    {
        first = null;
        last = null;
        count = 0;
    }

        //Method to determine whether the list is empty.
        //Postcondition: Returns true if the list is empty;
        //               false otherwise.
    public boolean isEmptyList()
    {
        return (first == null);
    }

        //Method to initialize the list to an empty state.
        //Postcondition: first = null, last = null,
        //               count = 0
    public void initializeList()
    {
        first = null;
        last = null;
        count = 0;
    }

        //Method to output the data contained in each node.
    public void print()
    {
        LinkedListNode current; //variable to traverse the list

        current = first;    //set current so that it points to
                            //the first node
        while(current != null) //while more data to print
        {
            System.out.print(current.info + " ");
            current = current.link;
        }
    }//end print

        //Method to return the number of nodes in the list.
        //Postcondition: The value of count is returned.
    public int length()
    {
        return count;
    }


        //Method to return a reference of the object containing
        //the data of the first node of the list.
        //Precondition: The list must exist and must not be empty.
        //Postcondition: The reference of the object that
        //               contains the info of the first node
        //               is returned.
    public DataElement front()
    {
        DataElement temp = first.info.getCopy();
        return temp;
    }

        //Method to return a reference of object containing
        //the data of the last node of the list.
        //Precondition: The list must exist and must not be empty.
        //Postcondition: The reference of the object that
        //               contains the info of the last node
        //               is returned.
    public DataElement back()
    {
        DataElement temp = last.info.getCopy();
        return temp;
    }

        //Method to determine whether searchItem is in the list.
        //Postcondition: Returns true if searchItem is found
        //               in the list; false otherwise.
    public abstract boolean search(DataElement searchItem);


        //Method to insert newItem in the list.
        //Postcondition: first points to the new list
        //               and newItem is inserted at the
        //               beginning of the list. Also,
        //               last points to the last node and
        //               count is incremented by 1.
    public void insertFirst(DataElement newItem)
    {
        LinkedListNode newNode;     //variable to create the
                                    //new node

        newNode = new LinkedListNode();     //create the new node
        newNode.info = newItem.getCopy();   //assign a copy of
                                            //newItem to the node
        newNode.link = first;   //insert newNode before first
        first = newNode;        //make first point to the
                                //actual first node

        if(last == null)        //if the list was empty, newNode is
                                //also the last node in the list
            last = newNode;

        count++;
    }

        //Method to insert newItem at the end of the list.
        //Postcondition: first points to the new list and
        //               newItem is inserted at the end
        //               of the list. Also, last points to
        //               the last node and
        //               count is incremented by 1.
    public void insertLast(DataElement newItem)
    {
        LinkedListNode newNode; //variable to create the new node

        newNode = new LinkedListNode();     //create the new node
        newNode.info = newItem.getCopy();   //assign a copy of
                                            //newItem to the node
        newNode.link = null;         //set the link field of
                                    //newNode to null

        if(first == null)   //if the list is empty, newNode is
                            //both the first and last node
        {
            first = newNode;
            last = newNode;
        }
        else     //if the list is not empty, insert newNode after last
        {
            last.link = newNode; //insert newNode after last
            last = newNode;     //set last to point to the actual last node
        }

        count++;
    }//end insertLast



        //Method to delete deleteItem from the list.
        //Postcondition: If found, the node containing
        //               deleteItem is deleted from the
        //               list. Also first points to the first
        //               node, last points to the last
        //               node of the updated list, and count
        //               is decremented by 1.
    public abstract void deleteNode(DataElement deleteItem);

        //Method to return a reference of the copy of otherList.
    private void copy(LinkedListClass otherList)
    {
        LinkedListNode newNode; //variable to create a node
        LinkedListNode current; //variable to traverse the list

        first = null;  //make this list empty

        if(otherList.first == null) //otherList is empty
        {
           first = null;
           last = null;
           count = 0;
        }
        else
        {
           count = otherList.count;
           current = otherList.first;  //current points to the
                                       //list to be copied

               //copy the first element
           first = new LinkedListNode();         //create the node
           first.info = current.info.getCopy();  //copy the info
           first.link = null;   //set the link field of
                                //the node to null
           last = first;        //make last point to the first node
           current = current.link; //make current point to the next
                                   //node of the list being copied

                //copy the remaining list
           while(current != null)
           {
               newNode = new LinkedListNode();
               newNode.info = current.info.getCopy();
               newNode.link = null;
               last.link = newNode;
               last = newNode;
               current = current.link;
           }//end while
        }//end else
    }//end copy


        //Method to return a reference of the copy of otherList.
    public void copyList(LinkedListClass otherList)
    {
        if(this != otherList)  //avoid self-copy
           copy(otherList);
    }

         //copy constructor
    public LinkedListClass(LinkedListClass otherList)
    {
        copy(otherList);
    }//end copy constructor
    
    public abstract void deleteAll(DataElement deleteItem);
    
    public abstract void deleteSmallest();
}
---------------------end of LinkedListClass.java---------------------------------

------------------------------UnorderedLinkedList.java-------------------------------

public class UnorderedLinkedList extends LinkedListClass
{

    public UnorderedLinkedList()
    {
        super();
    }

    public UnorderedLinkedList(UnorderedLinkedList otherList)
    {
        super(otherList);
    }

        //Method to determine whether searchItem is in
        //the list.
        //Postcondition: Returns true if searchItem is found
        //               in the list; false otherwise.
    public boolean search(DataElement searchItem)
    {
        LinkedListNode current; //variable to traverse the list
        boolean found;

        current = first;    //set current to point to the first
                            //node in the list

        found = false;    //set found to false

        while(current != null && !found) //search the list
            if(current.info.equals(searchItem))  //item is found
                found = true;
            else
               current = current.link; //make current point to
                                       //the next node
        return found;
    }


        //Method to delete deleteItem from the list.
        //Postcondition: If found, the node containing
        //               deleteItem is deleted from the
        //               list. Also first points to the first
        //               node, last points to the last
        //               node of the updated list, and count
        //               is decremented by 1.
    public void deleteNode(DataElement deleteItem)
    {
        LinkedListNode current; //variable to traverse the list
        LinkedListNode trailCurrent; //variable just before current
        boolean found;

        if(first == null)    //Case 1; the list is empty
           System.err.println("Cannot delete from an empty list.");
        else
        {
           if(first.info.equals(deleteItem)) //Case 2
           {
              first = first.link;

              if(first == null)    //the list had only one node
                 last = null;
              count--;
           }
           else  //search the list for the node with the given info
           {
              found = false;
              trailCurrent = first;   //set trailCurrent to point to
                                      //the first node
              current = first.link;   //set current to point to the
                                      //second node

              while(current != null && !found)
              {
                  if(current.info.equals(deleteItem))
                     found = true;
                  else
                  {
                      trailCurrent = current;
                      current = current.link;
                  }
              }//end while

              if(found) //Case 3; if found, delete the node
              {
                  count--;
                  trailCurrent.link = current.link;

                  if(last == current)   //node to be deleted was
                                        //the last node
                     last = trailCurrent;  //update the value of last
              }
              else
                 System.out.println("Item to be deleted is "
                                  + "not in the list.");
           }//end else
        }//end else
    }//end deleteNode


    public void deleteAll(DataElement deleteItem)
    {
        LinkedListNode current; //variable to traverse the list
        LinkedListNode trailCurrent = null; //variable just before current

        if(first == null)    //Case 1; list is empty.
            System.err.println("Can not delete from an empty list.");
        else
        {
            current = first;

            while(current != null)
            {
                if(current.info.equals(deleteItem))
                {
                    if(current == first)
                    {
                        first = first.link;
                        current = first;

                        if(first == null)
                            last = null;
                    }
                    else
                    {
                        trailCurrent.link = current.link;

                        if(current == last)
                            last = trailCurrent;

                        current = trailCurrent.link;
                    }
                }
                else
                {
                    trailCurrent = current;
                    current = current.link;
                }
            } //end while
        }

    } //end deleteAll

    public void deleteSmallest()
    {
        LinkedListNode current; //variable to traverse the list
        LinkedListNode trailCurrent; //variable just before current

        LinkedListNode small;
        LinkedListNode trailSmall = null;

        if(first == null)
            System.err.println("Can not delete from an empty list.");
        else
            if(first.link == null)
            {
                first = null;
                last = null;
            }
            else
            {
                small = first;
                trailCurrent = first;
                current = first.link;

                while(current != null)
                {
                    if(small.info.compareTo(current.info) > 0)
                    {
                        trailSmall = trailCurrent;
                        small = current;
                    }

                    trailCurrent = current;
                    current = current.link;
                }

                if(small == first)
                    first = first.link;
                else
                {
                    trailSmall.link = small.link;

                    if(small == last)
                        last = trailSmall;
                }
            }
    }//end deleteSmallest
}
------------------------------end of UnorderedLinkedList.java-------------------------------


No comments:

Post a Comment