Advertisement
Guest User

Untitled

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