Advertisement
Guest User

Untitled

a guest
Nov 26th, 2014
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 13.46 KB | None | 0 0
  1. package SortedLinkedList;
  2.  
  3. /**
  4.    A class that implements the ADT sorted list by using a chain of linked nodes.
  5.    Uses an array of headers (firstNode).
  6.  
  7.    @author CSIT265 (see textbook for outline)
  8.    @version 3.0
  9. */
  10. public class SortedLinkedList<T extends Comparable<? super T>>
  11.     implements SortedListInterface<T>
  12. {
  13.  
  14.    private int  numberOfHeaders;  // number of chains
  15.    private Headers[] firstNodeOnChain; // reference to first node of chain
  16.    private int[] numberOfEntriesOnChain;  // number entries per chain
  17.    
  18.  
  19.    public SortedLinkedList(int maxKeys)  // constructor number of keys
  20.    {
  21.        numberOfEntriesOnChain = new int[maxKeys];
  22.        firstNodeOnChain = new Headers[maxKeys];
  23.        for (int index=0; index < maxKeys; index ++)
  24.        {     
  25.            numberOfEntriesOnChain[index] = 0;
  26.            firstNodeOnChain[index] = new Headers();
  27.        }
  28.      
  29.        numberOfHeaders = 0;
  30.    } // end default constructor
  31.  
  32.    public void add(T newEntry, String entryKey)  // object and key
  33.    {
  34.       Node newNode = new Node(newEntry, null);
  35.       int chain;
  36.       int resp;
  37.    
  38.       chain = findHeader(firstNodeOnChain, numberOfHeaders, entryKey);  // binary search array of headers
  39.      
  40.       if (chain == -1)  // no header
  41.       {
  42.           chain = addNewHeader(firstNodeOnChain, numberOfEntriesOnChain, numberOfHeaders, entryKey); // insert key into header array
  43.           firstNodeOnChain[chain].setFirst(newNode);  // set link to node
  44.           numberOfHeaders ++;
  45.          
  46.       }
  47.          
  48.       else
  49.       {
  50.           Node nodeBefore = getNodeBefore(newEntry, chain);
  51.                
  52.           if (isEmpty(chain+1) || (nodeBefore == null)) // add at beginning
  53.           {
  54.               newNode.setNextNode(firstNodeOnChain[chain].getFirst());
  55.               firstNodeOnChain[chain].setFirst(newNode);
  56.           }
  57.           else                                   // add after nodeBefore
  58.           {
  59.               Node nodeAfter = nodeBefore.getNextNode();
  60.               newNode.setNextNode(nodeAfter);
  61.               nodeBefore.setNextNode(newNode);
  62.           }  // end else not first
  63.              
  64.       } // end walk chain
  65.  
  66.       numberOfEntriesOnChain[chain]++;
  67.      
  68.    } // end add
  69.    
  70.  
  71.    /* Uses binary search to determine if the searchArg is in the list
  72.    
  73.    @param headers the list, length of list, and search argument
  74.    
  75.    @return position in the list or -1  */
  76.    
  77.    public int findHeader(Headers[] headers, int length, String searchArg)
  78.    {
  79.        int first = 0;
  80.        int last = length-1;
  81.        int mid = 0;
  82.        boolean found = false;
  83.        
  84.        while (first <= last && !found)
  85.        {
  86.            mid = (first + last) / 2;
  87.            if (headers[mid].getKey().equals(searchArg))
  88.                found = true;
  89.            else
  90.                if (headers[mid].getKey().compareTo(searchArg) < 0)
  91.                    first = mid + 1;
  92.                else
  93.                    last = mid - 1;
  94.        }
  95.  
  96.        if (found)
  97.            return mid;
  98.  
  99.        else
  100.            return -1;
  101.    }//end findHeader
  102.    
  103.    public T[] getObjectsForKey (String key)
  104.    {
  105.        
  106.        int index = findHeader(firstNodeOnChain, numberOfHeaders, key);
  107.        int size = getLength(index);
  108.        T[] fly = (T[])new Comparable[size];
  109.        if (index != -1)
  110.        {
  111.            Node currentNode = firstNodeOnChain[index].getFirst();
  112.            int cnt = 0;
  113.            while(currentNode != null)
  114.                {
  115.                fly[cnt] = (T)currentNode.getData();
  116.                ++cnt;
  117.                currentNode = currentNode.getNextNode();
  118.            
  119.                }
  120.                 return fly;
  121.         }       else
  122.                 return fly;
  123.        }
  124.  /* Inserts into ordered header list the new element
  125.    
  126.    @param headers the list, length of list, and new key */
  127.    
  128.    public int addNewHeader(Headers[] headers, int[] numberOfEntriesOnChain, int length, String newKey)
  129.    {
  130.        int index = length-1;
  131.        boolean found = false;
  132.        String tempKey;
  133.        Node tempNode;
  134.        
  135.        while (index >= 0 && ! found)
  136.        {
  137.            tempKey = headers[index].getKey();
  138.            if (tempKey.compareTo(newKey) > 0)
  139.            {
  140.                // move down
  141.                tempNode = headers[index].getFirst();
  142.                headers[index+1].setInfo(tempKey, tempNode);
  143.                numberOfEntriesOnChain[index+1] = numberOfEntriesOnChain[index];
  144.                index --;
  145.            }
  146.            else
  147.                found = true;
  148.        }
  149.        index ++;
  150.      
  151.        headers[index].setKey(newKey);
  152.        headers[index].setFirst(null);  
  153.        numberOfEntriesOnChain[index] = 0;
  154.        
  155.        return index;
  156.    }
  157.    
  158.    
  159.    /* Finds the node that is before the node that
  160.       should or does contain a given entry.
  161.       @param anEntry  the object to be located and the chain #
  162.       @return either a reference to the node that is before the node
  163.               that contains or should contain anEntry, or null if
  164.               no prior node exists (that is, if anEntry belongs at
  165.               the beginning of the list) */
  166.    private Node<T> getNodeBefore(T anEntry, int chain)
  167.    {
  168.       Node nodeBefore = null;
  169.      
  170.       if (numberOfEntriesOnChain[chain] > 0) // there is a list
  171.       {  
  172.           Node currentNode = firstNodeOnChain[chain].getFirst();
  173.          
  174.           if (currentNode != null)
  175.           {
  176.               while ( (currentNode != null) &&
  177.                       (anEntry.compareTo((T)currentNode.getData()) > 0) )
  178.               {
  179.                   nodeBefore = currentNode;
  180.                   currentNode = currentNode.getNextNode();
  181.               } // end while
  182.           }
  183.            
  184.       }
  185.    
  186.       return nodeBefore;
  187.    } // end getNodeBefore
  188.  
  189.    
  190.    /* Removes entry
  191.    @param anEntry  the object to be removed and the key
  192.    @return true/false */
  193.    public boolean remove(T anEntry, String entryKey)
  194.    {
  195.       boolean found = false;
  196.  
  197.       if (numberOfHeaders > 0)  
  198.       {
  199.          
  200.           int chain = findHeader(firstNodeOnChain, numberOfHeaders, entryKey);
  201.           if (chain != -1)  // there is a chain
  202.           {
  203.               Node nodeToRemove;
  204.               Node nodeBefore = getNodeBefore(anEntry, chain);
  205.  
  206.               if (nodeBefore == null)  // first node on list
  207.                   nodeToRemove = firstNodeOnChain[chain].getFirst();
  208.               else
  209.                   nodeToRemove = nodeBefore.getNextNode();
  210.            
  211.               if ((nodeToRemove != null) && anEntry.compareTo((T)nodeToRemove.getData()) == 0 )  // fields match
  212.               {
  213.                   found = true;
  214.            
  215.                   if (nodeBefore == null)      
  216.                       firstNodeOnChain[chain].setFirst(nodeToRemove.getNextNode());  // new first node
  217.                   else
  218.                   {                                                    
  219.                       Node nodeAfter = nodeToRemove.getNextNode();  
  220.                       nodeBefore.setNextNode(nodeAfter);    // node before linked to node after                
  221.                   } // end if
  222.               }
  223.               numberOfEntriesOnChain[chain]--;
  224.                  
  225.         } // end if  there is a chain
  226.       } // end if  there is a list
  227.  
  228.       return found;
  229.    } // end remove
  230.  
  231.    /* Removes entry
  232.    @param position on chain and the chain
  233.    @return object removed  */
  234.    public T remove(int givenPosition, int chain)
  235.    {
  236.        T result = null;                           // return value
  237.        chain--;
  238.        if (numberOfEntriesOnChain[chain] >= 0) // there is a chain
  239.        {
  240.            if ((givenPosition >= 1) && (givenPosition <= numberOfEntriesOnChain[chain])) // within limit
  241.            {
  242.                assert !isEmpty(chain+1);
  243.  
  244.                if (givenPosition == 1)                 // case 1: remove first entry
  245.                {
  246.                    result = (T)firstNodeOnChain[chain].getFirst().getData();        // save entry to be removed
  247.                    firstNodeOnChain[chain].setFirst(firstNodeOnChain[chain].getFirst().getNextNode());
  248.                }
  249.                else                                    // case 2: givenPosition > 1
  250.                {
  251.                    Node nodeBefore = getNodeAt(givenPosition-1, chain+1);
  252.                    Node nodeToRemove = nodeBefore.getNextNode();
  253.                    Node nodeAfter = nodeToRemove.getNextNode();
  254.                    nodeBefore.setNextNode(nodeAfter);   // disconnect the node to be removed
  255.                    result = (T)nodeToRemove.getData();     // save entry to be removed
  256.                } // end if
  257.  
  258.                numberOfEntriesOnChain[chain]--;
  259.            } // end if
  260.        } // end if there is a chain
  261.        return result;                             // return removed entry, or
  262.                                                  // null if operation fails
  263.    } // end remove  
  264.    
  265.    /* Tests position of object on the chain
  266.    @param objec and  key
  267.    @return position (1 to numberOfEntriesOnChain  */
  268.    
  269.            
  270.            
  271.    public int getPosition(T anEntry, String entryKey)
  272.    {
  273.        int position = 0;
  274.        boolean found = false;
  275.        
  276.        if (numberOfHeaders > 0)  // there are chains
  277.        {
  278.            int chain = findHeader(firstNodeOnChain, numberOfHeaders, entryKey);
  279.            if (chain != -1)  // there is a chain for the key
  280.            {
  281.                Node currentNode = firstNodeOnChain[chain].getFirst();
  282.                
  283.                position = 1;
  284.      
  285.                while ( (currentNode != null) && !found) // sequential walk
  286.                {
  287.                    if (anEntry.compareTo((T)currentNode.getData()) == 0)
  288.                        found = true;
  289.                    else
  290.                    {
  291.                        currentNode = currentNode.getNextNode();
  292.                        position++;
  293.                    }
  294.                } // end while
  295.  
  296.                if ( (currentNode == null) || anEntry.compareTo((T)currentNode.getData()) != 0)  // not found
  297.                    position = -position;
  298.            }
  299.            return position;
  300.        }
  301.        else
  302.            return -1;
  303.    } // end getPosition
  304.  
  305.    /* Clears all headers and sets numberOfEntriesOnChain to 0
  306.      */
  307.    public final void clear()
  308.    {
  309.       for (int index=0; index < numberOfHeaders; index++)
  310.       {
  311.           firstNodeOnChain[index].setFirst(null);
  312.           firstNodeOnChain[index].setKey("");
  313.           numberOfEntriesOnChain[index] = 0;
  314.       }
  315.       numberOfHeaders = 0;
  316.      
  317.    } // end clear
  318.  
  319.    /* gets object in a specific position on a specific chain
  320.    @param position and chain
  321.    @return object  */
  322.    public T getEntry(int givenPosition, int chain)
  323.    {
  324.       T result = null;  // result to return
  325.  
  326.       if ((givenPosition >= 1) && (givenPosition <= numberOfEntriesOnChain[chain-1]))  // in bounds
  327.       {
  328.          assert !isEmpty(chain);
  329.          result = (T)getNodeAt(givenPosition, chain).getData();
  330.       } // end if
  331.          
  332.       return result;
  333.    } // end getEntry
  334.  
  335.    /* List contains object with specific key
  336.    @param Object and Key
  337.    @return true/false  */
  338.    public boolean contains(T anEntry, String entryKey)
  339.    {
  340.       boolean found = false;
  341.       int chain = findHeader(firstNodeOnChain, numberOfHeaders, entryKey);
  342.      
  343.       if (chain == -1)
  344.       {
  345.           return false;
  346.       }
  347.              
  348.       Node currentNode = firstNodeOnChain[chain].getFirst();
  349.  
  350.       while (!found && (currentNode != null))  // sequentially walk the chain
  351.       {
  352.           if (anEntry.compareTo((T)currentNode.getData()) == 0)
  353.           {
  354.               found = true;
  355.           }
  356.           else
  357.           {
  358.               currentNode = currentNode.getNextNode();
  359.           }
  360.       } // end while
  361.  
  362.       return found;
  363.    } // end contains
  364.  
  365.    /* gets length of list
  366.       @return count of nodes  */
  367.    public int getLength()
  368.    {
  369.        int num = 0;
  370.    
  371.        for (int index=0; index < numberOfHeaders; index++)
  372.           num = num + numberOfEntriesOnChain[index];
  373.        
  374.        return num;
  375.    } // end getLength
  376.  
  377.    /* gets length of specific chain
  378.      @param chain
  379.    @return count of nodes on chain  */
  380.    public int getLength(int chain)
  381.    {
  382.        return numberOfEntriesOnChain[chain-1];
  383.    } // end getLength
  384.  
  385.    /* List empty
  386.     @return true/false  */
  387.    public boolean isEmpty()
  388.    {
  389.       if (numberOfHeaders == 0)
  390.       {
  391.          return true;
  392.       }
  393.       else
  394.       {
  395.           return false;
  396.       }  
  397.    } // end isEmpty
  398.    
  399.    /* Specific chain empty
  400.     * @param chain
  401.    @return true/false  */
  402.    public boolean isEmpty(int chain)
  403.    {
  404.       if (numberOfEntriesOnChain[chain-1] == 0)
  405.       {
  406.          return true;
  407.       }
  408.       else
  409.       {
  410.          return false;
  411.       } // end if
  412.          
  413.    } // end isEmpty
  414.  
  415.    /* List full
  416.    @return false  */
  417.    public boolean isFull()
  418.    {
  419.       return false;
  420.    } // end isFull
  421.    
  422.    /* Get Node at specific position on specific chain
  423.    @param position and chain
  424.    @return Object*/
  425.    private Node getNodeAt(int givenPosition, int chain)
  426.    {
  427.        // chain exists and within bounds
  428.       assert !isEmpty(chain) && (1 <= givenPosition) && (givenPosition <= numberOfEntriesOnChain[chain-1]);
  429.       Node currentNode = firstNodeOnChain[chain-1].getFirst();
  430.  
  431.          // traverse the list to locate the desired node
  432.       for (int counter = 2; counter <= givenPosition; counter++)  // sequentially walk list
  433.          currentNode = currentNode.getNextNode();
  434.  
  435.       assert currentNode != null;
  436.       return currentNode;
  437.    } // end getNodeAt
  438.  
  439.    public T[] toArray()
  440.    {
  441.       // the cast is safe because the new array contains null entries
  442.       @SuppressWarnings("unchecked")
  443.       int chain, index = 0;
  444.       int num = 0;
  445.       int count = 0;
  446.      
  447.       for (chain=0; chain < numberOfHeaders; chain ++)
  448.       {
  449.           num = num + numberOfEntriesOnChain[chain] ;
  450.       }
  451.          
  452.       T[] result = (T[])new Comparable[num]; // warning: [unchecked] unchecked cast
  453.      
  454.       for (chain = 0; chain < numberOfHeaders; chain ++)
  455.       {
  456.           Node currentNode = firstNodeOnChain[chain].getFirst();
  457.           System.out.println(chain + " " + currentNode.getData().toString());
  458.           index = 0;
  459.           while ((index < numberOfEntriesOnChain[chain]) && (currentNode != null))
  460.           {
  461.               result[count] = (T)currentNode.getData();
  462.               currentNode = currentNode.getNextNode();
  463.               index++;
  464.               count++;
  465.           } // end while next on specific chain
  466.       }  // end of for - next chain
  467.       return result;
  468.    } // end toArray
  469.  
  470.  } // end SortedLinkedList
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement