Advertisement
Guest User

Untitled

a guest
Nov 28th, 2014
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 13.50 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.      
  102.    }
  103.    //end findHeader
  104.    
  105.    public T[] getObjectsForKey (String key)
  106.    {
  107.        
  108.        int index = findHeader(firstNodeOnChain, numberOfHeaders, key);
  109.  
  110.        int size = getLength(index);
  111.      
  112.        T[] fly = (T[])new Comparable[size];
  113.        if (index != -1)
  114.        {
  115.            Node currentNode = firstNodeOnChain[index].getFirst();
  116.            int cnt = 0;
  117.            while(currentNode != null)
  118.                {
  119.                fly[cnt] = (T)currentNode.getData();
  120.                ++cnt;
  121.                currentNode = currentNode.getNextNode();
  122.            
  123.                }
  124.                 return fly;
  125.         }       else
  126.                 return fly;
  127.        }
  128.  /* Inserts into ordered header list the new element
  129.    
  130.    @param headers the list, length of list, and new key */
  131.    
  132.    public int addNewHeader(Headers[] headers, int[] numberOfEntriesOnChain, int length, String newKey)
  133.    {
  134.        int index = length-1;
  135.        boolean found = false;
  136.        String tempKey;
  137.        Node tempNode;
  138.        
  139.        while (index >= 0 && ! found)
  140.        {
  141.            tempKey = headers[index].getKey();
  142.            if (tempKey.compareTo(newKey) > 0)
  143.            {
  144.                // move down
  145.                tempNode = headers[index].getFirst();
  146.                headers[index+1].setInfo(tempKey, tempNode);
  147.                numberOfEntriesOnChain[index+1] = numberOfEntriesOnChain[index];
  148.                index --;
  149.            }
  150.            else
  151.                found = true;
  152.        }
  153.        index ++;
  154.      
  155.        headers[index].setKey(newKey);
  156.        headers[index].setFirst(null);  
  157.        numberOfEntriesOnChain[index] = 0;
  158.        
  159.        return index;
  160.    }
  161.    
  162.  
  163.    /* Finds the node that is before the node that
  164.       should or does contain a given entry.
  165.       @param anEntry  the object to be located and the chain #
  166.       @return either a reference to the node that is before the node
  167.               that contains or should contain anEntry, or null if
  168.               no prior node exists (that is, if anEntry belongs at
  169.               the beginning of the list) */
  170.    private Node<T> getNodeBefore(T anEntry, int chain)
  171.    {
  172.       Node nodeBefore = null;
  173.      
  174.       if (numberOfEntriesOnChain[chain] > 0) // there is a list
  175.       {  
  176.           Node currentNode = firstNodeOnChain[chain].getFirst();
  177.          
  178.           if (currentNode != null)
  179.           {
  180.               while ( (currentNode != null) &&
  181.                       (anEntry.compareTo((T)currentNode.getData()) > 0) )
  182.               {
  183.                   nodeBefore = currentNode;
  184.                   currentNode = currentNode.getNextNode();
  185.               } // end while
  186.           }
  187.            
  188.       }
  189.    
  190.       return nodeBefore;
  191.    } // end getNodeBefore
  192.  
  193.    
  194.    /* Removes entry
  195.    @param anEntry  the object to be removed and the key
  196.    @return true/false */
  197.    public boolean remove(T anEntry, String entryKey)
  198.    {
  199.       boolean found = false;
  200.  
  201.       if (numberOfHeaders > 0)  
  202.       {
  203.          
  204.           int chain = findHeader(firstNodeOnChain, numberOfHeaders, entryKey);
  205.           if (chain != -1)  // there is a chain
  206.           {
  207.               Node nodeToRemove;
  208.               Node nodeBefore = getNodeBefore(anEntry, chain);
  209.  
  210.               if (nodeBefore == null)  // first node on list
  211.                   nodeToRemove = firstNodeOnChain[chain].getFirst();
  212.               else
  213.                   nodeToRemove = nodeBefore.getNextNode();
  214.            
  215.               if ((nodeToRemove != null) && anEntry.compareTo((T)nodeToRemove.getData()) == 0 )  // fields match
  216.               {
  217.                   found = true;
  218.            
  219.                   if (nodeBefore == null)      
  220.                       firstNodeOnChain[chain].setFirst(nodeToRemove.getNextNode());  // new first node
  221.                   else
  222.                   {                                                    
  223.                       Node nodeAfter = nodeToRemove.getNextNode();  
  224.                       nodeBefore.setNextNode(nodeAfter);    // node before linked to node after                
  225.                   } // end if
  226.               }
  227.               numberOfEntriesOnChain[chain]--;
  228.                  
  229.         } // end if  there is a chain
  230.       } // end if  there is a list
  231.  
  232.       return found;
  233.    } // end remove
  234.  
  235.    /* Removes entry
  236.    @param position on chain and the chain
  237.    @return object removed  */
  238.    public T remove(int givenPosition, int chain)
  239.    {
  240.        T result = null;                           // return value
  241.        chain--;
  242.        if (numberOfEntriesOnChain[chain] >= 0) // there is a chain
  243.        {
  244.            if ((givenPosition >= 1) && (givenPosition <= numberOfEntriesOnChain[chain])) // within limit
  245.            {
  246.                assert !isEmpty(chain+1);
  247.  
  248.                if (givenPosition == 1)                 // case 1: remove first entry
  249.                {
  250.                    result = (T)firstNodeOnChain[chain].getFirst().getData();        // save entry to be removed
  251.                    firstNodeOnChain[chain].setFirst(firstNodeOnChain[chain].getFirst().getNextNode());
  252.                }
  253.                else                                    // case 2: givenPosition > 1
  254.                {
  255.                    Node nodeBefore = getNodeAt(givenPosition-1, chain+1);
  256.                    Node nodeToRemove = nodeBefore.getNextNode();
  257.                    Node nodeAfter = nodeToRemove.getNextNode();
  258.                    nodeBefore.setNextNode(nodeAfter);   // disconnect the node to be removed
  259.                    result = (T)nodeToRemove.getData();     // save entry to be removed
  260.                } // end if
  261.  
  262.                numberOfEntriesOnChain[chain]--;
  263.            } // end if
  264.        } // end if there is a chain
  265.        return result;                             // return removed entry, or
  266.                                                  // null if operation fails
  267.    } // end remove  
  268.    
  269.    /* Tests position of object on the chain
  270.    @param objec and  key
  271.    @return position (1 to numberOfEntriesOnChain  */
  272.    
  273.            
  274.            
  275.    public int getPosition(T anEntry, String entryKey)
  276.    {
  277.        int position = 0;
  278.        boolean found = false;
  279.        
  280.        if (numberOfHeaders > 0)  // there are chains
  281.        {
  282.            int chain = findHeader(firstNodeOnChain, numberOfHeaders, entryKey);
  283.            if (chain != -1)  // there is a chain for the key
  284.            {
  285.                Node currentNode = firstNodeOnChain[chain].getFirst();
  286.                
  287.                position = 1;
  288.      
  289.                while ( (currentNode != null) && !found) // sequential walk
  290.                {
  291.                    if (anEntry.compareTo((T)currentNode.getData()) == 0)
  292.                        found = true;
  293.                    else
  294.                    {
  295.                        currentNode = currentNode.getNextNode();
  296.                        position++;
  297.                    }
  298.                } // end while
  299.  
  300.                if ( (currentNode == null) || anEntry.compareTo((T)currentNode.getData()) != 0)  // not found
  301.                    position = -position;
  302.            }
  303.            return position;
  304.        }
  305.        else
  306.            return -1;
  307.    } // end getPosition
  308.  
  309.    /* Clears all headers and sets numberOfEntriesOnChain to 0
  310.      */
  311.    public final void clear()
  312.    {
  313.       for (int index=0; index < numberOfHeaders; index++)
  314.       {
  315.           firstNodeOnChain[index].setFirst(null);
  316.           firstNodeOnChain[index].setKey("");
  317.           numberOfEntriesOnChain[index] = 0;
  318.       }
  319.       numberOfHeaders = 0;
  320.      
  321.    } // end clear
  322.  
  323.    /* gets object in a specific position on a specific chain
  324.    @param position and chain
  325.    @return object  */
  326.    public T getEntry(int givenPosition, int chain)
  327.    {
  328.       T result = null;  // result to return
  329.  
  330.       if ((givenPosition >= 1) && (givenPosition <= numberOfEntriesOnChain[chain-1]))  // in bounds
  331.       {
  332.          assert !isEmpty(chain);
  333.          result = (T)getNodeAt(givenPosition, chain).getData();
  334.       } // end if
  335.          
  336.       return result;
  337.    } // end getEntry
  338.  
  339.    /* List contains object with specific key
  340.    @param Object and Key
  341.    @return true/false  */
  342.    public boolean contains(T anEntry, String entryKey)
  343.    {
  344.       boolean found = false;
  345.       int chain = findHeader(firstNodeOnChain, numberOfHeaders, entryKey);
  346.      
  347.       if (chain == -1)
  348.       {
  349.           return false;
  350.       }
  351.              
  352.       Node currentNode = firstNodeOnChain[chain].getFirst();
  353.  
  354.       while (!found && (currentNode != null))  // sequentially walk the chain
  355.       {
  356.           if (anEntry.compareTo((T)currentNode.getData()) == 0)
  357.           {
  358.               found = true;
  359.           }
  360.           else
  361.           {
  362.               currentNode = currentNode.getNextNode();
  363.           }
  364.       } // end while
  365.  
  366.       return found;
  367.    } // end contains
  368.  
  369.    /* gets length of list
  370.       @return count of nodes  */
  371.    public int getLength()
  372.    {
  373.        int num = 0;
  374.    
  375.        for (int index=0; index < numberOfHeaders; index++)
  376.           num = num + numberOfEntriesOnChain[index];
  377.        
  378.        return num;
  379.    } // end getLength
  380.  
  381.    /* gets length of specific chain
  382.      @param chain
  383.    @return count of nodes on chain  */
  384.    public int getLength(int chain)
  385.    {
  386.        return numberOfEntriesOnChain[chain-1];
  387.        
  388.    } // end getLength
  389.  
  390.    /* List empty
  391.     @return true/false  */
  392.    public boolean isEmpty()
  393.    {
  394.       if (numberOfHeaders == 0)
  395.       {
  396.          return true;
  397.       }
  398.       else
  399.       {
  400.           return false;
  401.       }  
  402.    } // end isEmpty
  403.    
  404.    /* Specific chain empty
  405.     * @param chain
  406.    @return true/false  */
  407.    public boolean isEmpty(int chain)
  408.    {
  409.       if (numberOfEntriesOnChain[chain-1] == 0)
  410.       {
  411.          return true;
  412.       }
  413.       else
  414.       {
  415.          return false;
  416.       } // end if
  417.          
  418.    } // end isEmpty
  419.  
  420.    /* List full
  421.    @return false  */
  422.    public boolean isFull()
  423.    {
  424.       return false;
  425.    } // end isFull
  426.    
  427.    /* Get Node at specific position on specific chain
  428.    @param position and chain
  429.    @return Object*/
  430.    private Node getNodeAt(int givenPosition, int chain)
  431.    {
  432.        // chain exists and within bounds
  433.       assert !isEmpty(chain) && (1 <= givenPosition) && (givenPosition <= numberOfEntriesOnChain[chain-1]);
  434.       Node currentNode = firstNodeOnChain[chain-1].getFirst();
  435.  
  436.          // traverse the list to locate the desired node
  437.       for (int counter = 2; counter <= givenPosition; counter++)  // sequentially walk list
  438.          currentNode = currentNode.getNextNode();
  439.  
  440.       assert currentNode != null;
  441.       return currentNode;
  442.    } // end getNodeAt
  443.  
  444.    public T[] toArray()
  445.    {
  446.       // the cast is safe because the new array contains null entries
  447.       @SuppressWarnings("unchecked")
  448.       int chain, index = 0;
  449.       int num = 0;
  450.       int count = 0;
  451.      
  452.       for (chain=0; chain < numberOfHeaders; chain ++)
  453.       {
  454.           num = num + numberOfEntriesOnChain[chain] ;
  455.       }
  456.          
  457.       T[] result = (T[])new Comparable[num]; // warning: [unchecked] unchecked cast
  458.      
  459.       for (chain = 0; chain < numberOfHeaders; chain ++)
  460.       {
  461.           Node currentNode = firstNodeOnChain[chain].getFirst();
  462.           System.out.println(chain + " " + currentNode.getData().toString());
  463.           index = 0;
  464.           while ((index < numberOfEntriesOnChain[chain]) && (currentNode != null))
  465.           {
  466.               result[count] = (T)currentNode.getData();
  467.               currentNode = currentNode.getNextNode();
  468.               index++;
  469.               count++;
  470.           } // end while next on specific chain
  471.       }  // end of for - next chain
  472.       return result;
  473.    } // end toArray
  474.  
  475.  } // end SortedLinkedList
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement