Linked List implementation

I am working on a ListNode and I need to provide implementation for a garbageCollection() method.
What the method needs to do is
// recalculate start address for each node in alloclist
// delete all but the first node in freelist,
// update start address and size of this single free block
Any ideas of how I can do this.

I am working on a ListNode and I need to provide
implementation for a garbageCollection() method. You're probably in a class discussing memory allocation. It's quite easy actually but it requires some insight. Good luck -:)

Similar Messages

  • What can be the error in this simple Linked List Implementation

    i have a linked list code that wont compile successfully. The code is
    //Lets try the Linked List 
    import java.util.*;
    class LinkedListDemo {
    public static void main ( String args[]){
         LinkedList l1=new LinkedList();
         l1.add( "A");
         l1.add(2);
         l1.add(3);
         l1.add(4);
         l1.add(5);
         l1.addFirst(6);
         l1.add(7);
         l1.add(8);
         l1.add(9);
         //Lets check what does the Linked List hold at this time
         System.out.println("Prsently the linked lis is having:  "+l1);
    }Problem is with the add method . Compiler error is that it doesnt recognize the symbol ie add method.

    i m sorry , java version is 1.4In that case, read up on the link jverd posted on AutoBoxing. You can only add Objects to a List. An int is a primitive, not an Object. You can try something like this:
    l1.add(new Integer(2));

  • How  to Implement a Chained Hash Table with Linked Lists

    I'm making a migration from C/C++ to Java, and my task is to implement a Chained Hash Table with a Linked List. My problem is to put the strings(in this case names) hashed by the table using de Division Metod (H(k)= k mod N) in to a Linked list that is handling the colisions. My table has an interface implemented(public boolean insert(), public boolean findItem(), public void remove()). Any Help is needed. Thanks for everyone in advance.

    OK. you have your hash table. What you want it to do is keep key/value pairs in linked lists, so that when there is a collision, you add the key/value pair to the linked list rather than searching for free space on the table.
    This means that whenever you add an item, you hash it out, check to see if there is already a linked list and if not, create one and put it in that slot. Then in either case you add the key/value pair to the linked list if the key is not already on the linked list. If it is there you have to decide whether your requirements are to give an error or allow duplicate keys or just keep or modify one or the other (old/new).
    When you are searching for a key, you hash it out once again and check to see if there is a linked list at that slot. If there is one, look for the key and if it's there, return it and if not, or if there was no linked list at that slot, return an error.
    You aren't clear on whether you can simply use the provided linked-list implementations in the Java Collections or whether you have to cobble the linked list yourself. In any case, it's up to you.
    Is this what you're asking?
    Doug

  • Help needed in linked lists...

    I have been working on this computer assignment lately but I still don't understand linked lists yet..I did an assignment on array based implementation and now I am supposed to do the same thing in linked list implementation..
    I need help on how to change this into a linked list implementation..any help would be appreciated. Thank you..below is the code for the array based implementation..the only thing that needs change here is after where is says Array-based implementation of the ADT list.
    public class ListArrayBasedDriver {
      public static void main(String [] args) {
        ListArrayBased myGroceryList = new ListArrayBased();
        myGroceryList.add(1,"milk");
        myGroceryList.add(2,"eggs");
        myGroceryList.add(3,"butter");
        myGroceryList.add(4,"pecans");
        myGroceryList.add(5,"apples");
        myGroceryList.add(6,"bread");
        myGroceryList.add(7,"chicken");
        myGroceryList.add(8,"rice");
        myGroceryList.add(9,"red beans");
        myGroceryList.add(10,"sausage");
        myGroceryList.add(11,"flour");
        printList(myGroceryList); //print out original List
        System.out.print("numItems is now: " + myGroceryList.size() + "\n");
        System.out.println("adding juice for 5th item...");
        myGroceryList.add (5, (Object) "juice");  //add juice
        System.out.println("item 5 is: " + myGroceryList.get(5)); //get position 5
        printList(myGroceryList);
        System.out.print("numItems is now: " + myGroceryList.size() + "\n");
        System.out.println("removing juice...");
        myGroceryList.remove (5); //remove item at position 5
        printList(myGroceryList);
        System.out.print("numItems is now: " + myGroceryList.size() + "\n");
      public static void printList(ListArrayBased myList)
            //method prints a list, numbering the values,  e.g, "1.  milk" .... "5.  juice".... etc.
            int i;
            for(i=1; i <= myList.size(); i++)
                String tempString = new String((String)myList.get(i));
                System.out.println(i+" "+ tempString);
    // Array-based implementation of the ADT list.
    class ListArrayBased {
        private static final int MAX_LIST = 50;
        private Object items[];  // an array of list items
        private int numItems;  // number of items in list
        public ListArrayBased()
        // creates an empty list
             items = new Object[MAX_LIST];
             numItems = 0;
        }  // end default constructor
        public boolean isEmpty()
          return (numItems == 0);
        } // end isEmpty
        public int size()
           return numItems;
        }  // end size
        public void removeAll()
          // Creates a new array; marks old array for
          // garbage collection.
          items = new Object[MAX_LIST];
          numItems = 0;
        } // end removeAll
        public void add(int index, Object item) throws  ListIndexOutOfBoundsException
          if (numItems > MAX_LIST)
            throw new ListException("ListException on add");
        }  // end if
          if (index >= 1 && index <= numItems+1)
            // make room for new element by shifting all items at
            // positions >= index toward the end of the
            // list (no shift if index == numItems+1)
            for (int pos = numItems; pos >= index; pos--) {
              items[translate(pos+1)] = items[translate(pos)];
          } // end for
          // insert new item
          items[translate(index)] = item;
          numItems++;
          else
          {  // index out of range
            throw new ListIndexOutOfBoundsException(
             "ListIndexOutOfBoundsException on add");
          }  // end if
        } //end add
        public Object get(int index) throws ListIndexOutOfBoundsException
          if (index >= 1 && index <= numItems)
            return items[translate(index)];
          else 
          {  // index out of range
            throw new ListIndexOutOfBoundsException(
              "ListIndexOutOfBoundsException on get");
          }  // end if
        } // end get
        public void remove(int index) throws ListIndexOutOfBoundsException
          if (index >= 1 && index <= numItems)
            // delete item by shifting all items at
            // positions > index toward the beginning of the list
            // (no shift if index == size)
                for (int pos = index+1; pos <= size(); pos++) {
                    items[translate(pos-1)] = items[translate(pos)];
          }  // end for
          numItems--;    
          else
          {  // index out of range
            throw new ListIndexOutOfBoundsException("ListIndexOutOfBoundsException on remove");
          }  // end if
        } // end remove
        private int translate(int position) {
        return position - 1;
       } // end translate
    }  // end ListArrayBased
    class ListException extends RuntimeException
      public ListException(String s)
        super(s);
      }  // end constructor
    }  // end ListException
    class ListIndexOutOfBoundsException
                extends IndexOutOfBoundsException {
      public ListIndexOutOfBoundsException(String s) {
        super(s);
      }  // end constructor
    }  // end ListIndexOutOfBoundsException

    Could someone check for me if this will work and if it doesn't what I need to do to make it work..Thanks...
    public class ListArrayBasedDriver {
      public static void main(String [] args) {
        ListArrayBased myGroceryList = new ListArrayBased();
        myGroceryList.add(1,"milk");
        myGroceryList.add(2,"eggs");
        myGroceryList.add(3,"butter");
        myGroceryList.add(4,"pecans");
        myGroceryList.add(5,"apples");
        myGroceryList.add(6,"bread");
        myGroceryList.add(7,"chicken");
        myGroceryList.add(8,"rice");
        myGroceryList.add(9,"red beans");
        myGroceryList.add(10,"sausage");
        myGroceryList.add(11,"flour");
        printList(myGroceryList); //print out original List
        System.out.print("numItems is now: " + myGroceryList.size() + "\n");
        System.out.println("adding juice for 5th item...");
        myGroceryList.add (5, (Object) "juice");  //add juice
        System.out.println("item 5 is: " + myGroceryList.get(5)); //get position 5
        printList(myGroceryList);
        System.out.print("numItems is now: " + myGroceryList.size() + "\n");
        System.out.println("removing juice...");
        myGroceryList.remove (5); //remove item at position 5
        printList(myGroceryList);
        System.out.print("numItems is now: " + myGroceryList.size() + "\n");
      public static void printList(ListArrayBased myList)
            //method prints a list, numbering the values,  e.g, "1.  milk" .... "5.  juice".... etc.
            int i;
            for(i=1; i <= myList.size(); i++)
                String tempString = new String((String)myList.get(i));
                System.out.println(i+" "+ tempString);
    // Linked List-based implementation of the ADT list.
    class ListNode
         //class to represent one node in a list
         class ListNode
              //package access members; List can access these directly
              Object data;
              ListNode nextNode;
              //contructor creates a ListNode that refers to object
              ListNode( Object object)
                   this( object, null );
              } //end ListNode one-argument constructor
              //constructor creates ListNode that refers to
              // Object and to the next ListNode
              ListNode ( Object object, ListNode node)
                   data = object;
                   nextNode = node;
              // end ListNode two-argument contructor
              //return reference to data in node
              Object getObject()
                   return data; // return Object in this mode
              //return reference to next node in list
              ListNode getNext()
                   return nextNode; // get next node
              } // end method getNext
    } //end class ListNode
    //class List Definition
    public class List
         private ListNode firstNode;
         private ListNode lastNode;
         private String name; // string like " list " used in printing
         //contructor creates empty List with " list " as the name
         public List()
              this(" list ");
         } //end List no-arguement constructor
    //contructor creates an empty list with a name
    public List( String listName )
         name = listname;
         firstNode = lastNode = null;
    } //end List no-arguement contructor
    //insert Object at front of List
    public void insertAtFront ( object insertItem )
         if ( isEmpty() ) //firstNode and lastNode refer to same object
              firstNode = lastNode = newListNode( insertItem );
         else // firstNode refers to new node
              firstNode = new ListNode ( insertItem, firstNode );
    } // end method insertAtFront
    // insert Object at end of List
    public void insert AtBack ( Object insertItem )
         if ( isEmpty() ) //firstNode and lastNode refer to same object
              firstNode = new ListNode ( insertItem );
         else // firstNode refers to new node
         firstNode = new ListNode (insertItem, firstNode );
    } // end method insertAtFront
    // insert Object at end of List
    public void insertAtBack ( Object insertItem )
         if ( isEmpty() ) //firstNode and LastNode refer to same Object
              firstNode = lastNode = new ListNode ( insertItem );
         else // lastNode = lastNode.nextNode = new ListNode ( insertItem );
    } // end method insertAtBack
    //remove first node from List
    public Object removeFromFront() throws EmptyListException
         if( isEmpty() ) //throw exception if list is empty
         throw new EmptyListException( name );
         object removedItem = firstNode.data; //retrieve data being removed
    // update references firstNode and lastNode
    if (firstNode == lastNode )
         firstNode =lastNode = null;
    else
         firstNode = firstNode.nextNode;
         return removedItem; // return removed node data
    } //end method removeFromFront
    //remove last node from List
    Public Object removeFromBack() throws EmptyListException
         If ( isEmpty() ) // throw exception if list is empty
              throw new EmptyListException( name );
         Object removedItem = lastNode.data; // retrieve data being removed
         // update references firstNode and lastNode
         If ( firstNode == lastNode )
              firstNode = lastNode = null;
         else // locate new last node
              ListNode current = firstNode;
              // loop while current node does not refer to lastNode
              while ( current.nextNode != lastNode )
                   current = current.nextNode;
              lastNode = current; // current is new lastNode
              current.nextNode = null;
         } // end else
         return removedItem; // return removed node data
    } // end method removeFromBack
    // determine whether list is empty
    public boolean isEmpty()
         return firstNode == null; // return true if list is empty
    }     // end method isEmpty
    //output List contents
    public void print()
         if (isEmpty() )
              System.out.printf(�Empty %s\n�, name );
              return;
         System.out.printf(�The %s is: �, name );
         ListNode current = firstNode;
         //while (current != null )
              System.out,printf(�%s �, current.data );
              current = current.nextNode;
         } //end while
         System.out.println( �\n� );
    } //end method print
    } end class List

  • Linked List trouble

    //I need to add a header node into this Linked list class and
    // i dont understand it. can anyone give me a few pointers.
    // This is the orginal code. What im trying to figure out is below.
    public abstract class LinkedList implements ListInterface
    protected class ListNode
    // Used to hold references tolist nodes for the linked list implementation
    protected Listable info; // the info in a list node
    protected ListNode next; // a link to the next node on the list
    protected ListNode list; // reference to the first node on the list
    protected int numItems; // Number of elements in the list
    protected ListNode currentPos; // Current position for iteration
    public LinkedList()
    // Creates an empty list object.
    numItems = 0;
    list = null;
    currentPos = null;
    public boolean isFull()
    // Determines whether this list is full.
    return false;
    public int lengthIs()
    // Determines the number of elements on this list.
    return numItems;
    public abstract boolean isThere (Listable item);
    // Determines if element matching item is on this list.
    public Listable retrieve (Listable item)
    // Returns a copy of the list element with the same key as item.
    ListNode location = list;
    boolean found = false;
    while (!found)
    if (item.compareTo(location.info) == 0) // if they match
    found = true;
    else
    location = location.next;
    return location.info.copy();
    public abstract void insert (Listable item);
    // Adds a copy of item to this list.
    public void delete (Listable item)
    // Deletes the element of this list whose key matches item�s key.
    ListNode location = list;
    // Locate node to be deleted.
    if (item.compareTo(location.info) == 0)
    list = list.next; // Delete first node.
    else
    while (item.compareTo(location.next.info) != 0)
    location = location.next;
    // Delete node at location.next.
    location.next = location.next.next;
    numItems--;
    public void reset()
    // Initializes current position for an iteration through this list.
    currentPos = list;
    public Listable getNextItem ()
    // Returns copy of the next element in list.
    Listable nextItemInfo = currentPos.info.copy();
    if (currentPos.next == null)
    currentPos = list;
    else
    currentPos = currentPos.next;
    return nextItemInfo;
    //now heres the part i dont get i need to make list point to a new
    // node say HeaderNode. Now wouldnt just...
    public LinkedList()
    // Creates an empty list object.
    numItems = 0;
    list.next = HeaderNode; //....this line do the trick???
    currentPos = null;
    I know that i cant use any insert methods to put it in, so what else could i possibly do?

    bump

  • Java Linked List Help

    Hey,
    I am having trouble understanding the Linked List implementation code given under the Node Operations part of this pdf.
    http://www.cs.berkeley.edu/~jrs/61b/lec/07.pdf
    public ListNode(int item, ListNode next) {
    this.item = item;
    this.next = next;
    public ListNode(int item) {
    this(item, null);
    ListNode l1 = new ListNode(7, new ListNode(0, new ListNode(6)));
    I understand the earlier implementation, but this one has me confused. Would someone please go through/explain the flow of this implementation with me?
    Thanks

    Well the code is pretty self explanitory.
    a ListNode class that has two fields. an int field item, and a ListNode field next.
    so when you create a ListNode object you can do so by one of two means passing one parameter or passing two parameters.
    if you pass one parameter then you have a ListNode which has an int say 1 and a ListNode object who's value is null.
    if you pass two parameters then you have a ListNode which has an int say 2 and a ListNode object who's value is the ListNode you pass to it.
    ex ListNode myNode = ListNode(1,new ListNode(2));
    so myNode now has an integer 1 and a reference to another ListNode which has an integer value of 2 and a reference to a null ListNode.
    hope this helps.

  • Linked lists revisited

    hi i have the base code for a linked list implementation:the list, the node, and the iterator position. But the assignment gets harder i have to use this class and have a file read in from the command line and store each word into nodes. I can almost implement this with the String Tokenizer and the buffereader stuff but my other problem comes when i have to represent a arbitrarily long integer value in nodes. Basically i must represent the addition or multiplication of a number such as 50003401 and represent it in nodes storing the coefficient and the exponent so like (5*10^7)+(3*10^3)+(4*10^2)+(1*10^0). I need some help!! How do you store the coefficients and exponents in nodes and have them multiply and deal with all the carries.

    Here is my code with spaces in between each class
    import java.util.*;
    import java.io.*;
    public class SortedLinkedList
    SortedListNode header; //The list header, references a SortedListNode
    // constructor: should initialize to an empty list.
    public SortedLinkedList()
         header= new SortedListNode(null);//
    // returns an iterator that references the head of the list
    public SortedLinkedListItr zeroth( )
         return new SortedLinkedListItr(header);//
    // returns true if the list is empty, false otherwise
    public boolean isEmpty( )
         return header.next == null;
    // returns an iterator that references the first item in the list
    public SortedLinkedListItr first( )
         return new SortedLinkedListItr(header.next);//
    // inserts the item referenced by x into the list in sorted order.
    public void insert(Comparable x)
         SortedLinkedListItr prev=zeroth();//
         SortedLinkedListItr curr=first();//
              while(curr!=null && x.compareTo(curr.retrieve())>0)
                   prev.advance();
                   curr.advance();
              insert(x);
    // returns an iterator that references the item x if it is found in the list
    public SortedLinkedListItr find(Comparable x)
         SortedListNode itr= header;//
         while( itr.next != null && !itr.next.element.equals(x))
              itr=itr.next;
              return new SortedLinkedListItr( itr );//
    // returns an iterator that references the item that precedes x in the list
    // (if such an item exists).
    public SortedLinkedListItr findPrevious(Comparable x)
         SortedListNode itr = header;//
         while(itr.next !=null && !itr.next.element.equals(x))
              itr = itr.next;
         return new SortedLinkedListItr(itr);//
    // removes the item x from the list, if it exists
    public void remove(Comparable x)
         SortedLinkedListItr p =findPrevious(x);//
         if ( p.current.next !=null )
         p.current.next = p.current.next.next;
    // prints the items in the list in the order that they appear in the list
    public void printList()
         if(isEmpty())
              System.out.print("The list is empty.");
         else
              SortedLinkedListItr itr = first();//
              for(; itr!=null; itr.advance())
                   System.out.print(itr.retrieve() + " ");
         System.out.println();
    public static void main(String[] args) throws IOException
              SortedLinkedList stringList = new SortedLinkedList();
              if (args.length != 1)
                   System.err.println("USAGE: java ReadData input-file\n");
              System.exit(1);
              String filename = args[0];
              FileReader fileReader = new FileReader(filename);
              BufferedReader bufferedReader = new BufferedReader(fileReader);
              System.out.println(filename + " has the following tokens in it:");
              String inputString = bufferedReader.readLine();
              while (inputString!=null)
              StringTokenizer tokenizer = new StringTokenizer(inputString);
              while (tokenizer.hasMoreTokens())
              String token = tokenizer.nextToken();
              stringList.insert(token);
                        inputString = bufferedReader.readLine();
              stringList.printList();
    public class SortedLinkedListItr
    SortedListNode current; //the node referenced by the iterator.
    //constructor: to be used within SortedLinkedList. Sets the iterator
    //to reference the node specified in the parameter.
    SortedLinkedListItr(SortedListNode theNode)
         current = theNode;
    //returns true if the iterator has advanced past the last node in the list.
    public boolean isPastEnd( )
              return (current == null);
    //returns the item currently referrenced by the iterator (null if the iterator
    //is past the end of the list.
    public Comparable retrieve( )
              if(
              return (current.element);
    // moves the iterator to the next item in the list (does nothing if the
    // iterator is past the end of the list.
    public void advance( )
              if (current!=null)
              current = current.next;
              else
              current=null;
    class SortedListNode
    // instance variables
    Comparable element; // the element being stored by this node
    SortedListNode next; // reference to the next item in the list
    //two constructors, one returns a null next, the other allows
    //it to be set to reference another node.
    SortedListNode(Comparable theElement)
              this(theElement, null);
    SortedListNode(Comparable theElement,SortedListNode n)
              element=theElement; next = n;
    }

  • Linked list troubles

    How do i put a headernode into this constructor?
    protected class ListNode
    // Used to hold references tolist nodes for the linked list implementation
    protected Listable info; // the info in a list node
    protected ListNode next; // a link to the next node on the list
    protected ListNode list; // reference to the first node on the list
    protected int numItems; // Number of elements in the list
    protected ListNode currentPos; // Current position for iteration
    public LinkedList()
    // Creates an empty list object.
    numItems = 0;
    list = null;
    currentPos = null;

    You mean...
    public LinkedList(ListNode nodeHeader)
      numItems = 0;
      list = nodeHeader;
      currentPos = null;

  • How to implement a linked list in oracle ?

    HI All
    I want to know if there a way to implement a linked list in oracle ?
    Thanks in Advanced
    Naama

    A linked list is an array of the relevant data plus an indicator of the next and previous entries, right?
    Sounds easily achievable with any of the plsql collection types.
    The simplest would be a plsql associative array of a record
    Assignments of records in collections is always a bit hamfisted compared to sql objects types though (IMO).
    Something like ?
    DECLARE
    TYPE r_payload IS RECORD
    (col1 number,
      col2 number);
    TYPE r_array_entry is RECORD
    (prev_entry PLS_INTEGER,
      next_entry PLS_INTEGER,
      payload    r_payload);
    TYPE t_array IS TABLE OF r_array_entry INDEX BY PLS_INTEGER;
    v_array t_array;
    BEGIN
    NULL;
    END; 
      The use case for such a structure in properly coded SQL & PL/SQL is possibly the harder question.

  • Implementing my own linked lists...aiiieee!

    Hi,
    I'm trying to implement my own linked list structure oftype String. It will eventually go to form a simple text editor, with each line of a file being loaded into its own String node.
    However, im having problems implementing the list itself :)
    So far ive got the file to read in succesfully, but now im stuck...how do i load up a line into a new node? and what about the head/tail nodes, they just confuse me! Do i have to write a seperate 'List' class and create an object of that, much like the LinkedList class with Java?
    Any help or a nudge in the right direction would be appreciated,
    TIA
    andrew
    PS code below ...
    =================================
    =================================
    import java.io.*;
    import java.util.*;
    class Editor {
    public static void main(String[] args) {
    ///LOAD UP THE TEXT FILE//////////////////////////////////////
         String file = "s.txt";
         String line;
         System.out.println(System.in);
         //testing here...
    StringNode alist = new StringNode(null,null);
         try{
              FileReader FR = new FileReader(file);
              BufferedReader BR = new BufferedReader(FR);
              while ( (line = BR.readLine()) != null ){
                   alist.addNodeAfter(line);
                   System.out.println(line);
                   }//while
         }//try
         catch(IOException e){
              System.out.println(file + " not found");
         }//catch
    ///COMMANDS///////////////////////////////////////////////////
    //text editor commands to be input via command line type console. how to grab inputs on return?
    }//main
    }//Editor
    //code to create a node...but now what?
         class StringNode
         private String data;
         private StringNode link;
         // constructor for initialisation
         public StringNode(String initialData, StringNode initialLink)
              data = initialData;
              link = initialLink;
         // accessor method to get the data from this node
         public String getData( )
              return data;
         // accessor method to get a reference to the next node after this node.
         public StringNode getLink( )
              return link;
         // modification method to set the data in this node.
         public void setData(String newData)
              data = newData;
         // modification method to set the link to the next node after this node
         public void setLink(StringNode newLink)
              link = newLink;
         // add a new node after this node
         public void addNodeAfter(String item)
              link = new StringNode(item, link);
         // modification method to remove the node after this node.
         public void removeNodeAfter( )
              link = link.link;
         // compute the number of nodes in a linked list
         public static int listLength(StringNode head)
              StringNode cursor;
              int answer;
              answer = 0;
              for (cursor = head; cursor != null; cursor = cursor.link)
                   answer++;
              return answer;
         // print the nodes in a linked list
         public static void listPrint(StringNode head)
              StringNode cursor;
              for (cursor = head; cursor != null; cursor = cursor.link)
                   System.out.println(cursor.getData());
         // print the nodes in a linked list skipping dummy node at head
         public static void listPrint2(StringNode head)
              StringNode cursor;
              for (cursor = head.link; cursor != null; cursor = cursor.link)
                   System.out.println(cursor.getData()+" ");
         // search for a particular piece of data in a linked list
         public static StringNode listSearch(StringNode head, String target)
              StringNode cursor;
              for (cursor = head; cursor != null; cursor = cursor.link)
                   if (target == cursor.data)
                        return cursor;
              return null;
    }

    You wouldn't by any chance be doing computer science at Cardiff university would you and have been given this as an assignment?

  • Implementation of Linked List class

    I am trying to implement the Linked List class for one week, but I couldn't figure it out. If you know, please let me know.

    Here is an example of a linked list. Hope that will help.
    // define a node of a linked list
    public class Node
    public int data; // point to data
    public Node next; // pointer to next node or point to null if end of list
    // listTest1
    public class ListTest1
    public static void main(String[] args)
    Node list;
    list = new Node();
    list.data = 3;
    list.next = new Node();
    list.next.data = 7;
    list.next.next = new Node();
    list.next.next.data = 12;
    list.next.next.next = null;
    Node current = list;
    while (current != null) {
    System.out.print(current.data + " ");
    current = current.next;
    System.out.println();
    // other listnode
    public class ListNode
    public int data;
    public ListNode next;
    public ListNode()
    // post: constructs a node with data 0 and null link
    this(0, null);
    public ListNode(int value)
    // post: constructs a node with given data and null link
    this(value, null);
    public ListNode(int value, ListNode link)
    // post: constructs a node with given data and given link
    data = value;
    next = link;
    Contents of ListTest2.java
    public class ListTest2
    public static void main(String[] args)
    ListNode list = new ListNode(3, new ListNode(7, new ListNode(12)));
    ListNode current = list;
    while (current != null) {
    System.out.print(current.data + " ");
    current = current.next;
    System.out.println();

  • Implementing Double Linked Lists

    I have been set a task creating a java class to implement the data cells of a double linked list, then improving on this class so that it will implemt the interface of a LinearList using a double linked list.
    HELP?!?!?!?!

    i have implemented a small method.u can implement the remaining methods as u want. I have not tested the code. Just for idea i am giving it. try it.
    public class Node{
         Node leftNode;
         Node rightNode;
         int data;
         public Node addNode(Node node,int data,int position){
              Node originalCopy=node;
              for(int i=0;i<position;i++){
                   Node tempNode=new Node();
                   tempNode.data=data;
                   tempNode.leftNode=node;
                   tempNode.rightNode=node.rightNode;
                   node=node.rightNode;
              return originalCopy;
    This class represents a Doubly linked list and it provides operations on it.

  • Help Implementing a queue as a circular linked list...

    I have a set of code that I need to implement a circular linked list into, but I am not sure how to approach it at all. If anyone can point me to some pseudo code or sample code that I can modify for my use, that would be great.
    I created a Class CircularQueue, which implements Queue, I just need to figure out how to write it.
    Heres the code I have:
    Queue Interface
    public interface Queue<ElementType> {
         public void enqueue(ElementType e);
         public ElementType dequeue();
         public ElementType front();
         public boolean isEmpty();
    Data Holder
    public class DataHolder<ElementType> {
         // instance variables
         private ElementType _data;
          * Constructor for objects of class DataHolder
         public DataHolder() {
              _data = null;
         public void setContents(ElementType anItem) {
              _data = anItem;
         public ElementType getContents() {
             return _data;
    DeqeueButton
    import javax.swing.*;
    import java.awt.event.*;
    public class DequeueButton extends JButton {
        // instance variables
        private Queue<SmartRectangle> _queue;
        private QueuePanel _queuePanel;
         * Constructor for objects of class DequeueButton
        public DequeueButton(QueuePanel aQueuePanel) {
            super("Dequeue");
            _queuePanel = aQueuePanel;
            _queue = aQueuePanel.getQueue();
            this.addActionListener(new DequeueButtonListener());
        private class DequeueButtonListener implements ActionListener {
            private final int MOVE_LENGTH = 25;    // square size + 5
            public void actionPerformed(ActionEvent e) {
                _queue.dequeue();   // remove item from queue
                _queuePanel.repaint();
    EnqueueButton
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class EnqueueButton extends JButton {
        // instance variables
        private Queue<SmartRectangle> _queue;
        private QueuePanel _queuePanel;
         * Constructor for objects of class EnqueueButton
        public EnqueueButton(QueuePanel aQueuePanel) {
            super("Enqueue");
            _queuePanel = aQueuePanel;
            _queue = _queuePanel.getQueue();
            this.addActionListener(new EnqueueButtonListener());
        private class EnqueueButtonListener implements ActionListener {
            private int _nextX, _nextY;
            private final int SQUARE_SIZE = 20;
            private final int MAX_X = 550;
            private final int MAX_Y = 350;
            private Color _currentColor;
            public EnqueueButtonListener() {
                _currentColor = Color.BLUE;
                _nextX = MAX_X;
                _nextY = MAX_Y;
            public void actionPerformed(ActionEvent e) {
                _queue.enqueue(new SmartRectangle(_nextX, _nextY, SQUARE_SIZE, SQUARE_SIZE, _currentColor, _queuePanel));
                this.changeColor();
                _nextX -= (SQUARE_SIZE+5);  // location of next square in line
                if (_nextX < 0)     // if we reach edge of window, wrap
                {   _nextY -= (SQUARE_SIZE+5);
                    _nextX = MAX_X;
                if (_nextY < 0)     // start over
                    _nextY = MAX_Y;
                _queuePanel.repaint();
            public void changeColor() {
                if (_currentColor == Color.BLUE)          
                    _currentColor = Color.RED;
                else if (_currentColor == Color.RED)      
                    _currentColor = Color.GREEN;
                else if (_currentColor == Color.GREEN)    
                    _currentColor = Color.YELLOW;
                else if (_currentColor == Color.YELLOW)   
                    _currentColor = Color.BLACK;
                else if (_currentColor == Color.BLACK)    
                    _currentColor = Color.BLUE;
    FrontButton
    import javax.swing.*;
    import java.awt.event.*;
    public class FrontButton extends JButton {
        // instance variables
        private Queue<SmartRectangle> _queue;
        private QueuePanel _queuePanel;
         * Constructor for objects of class DequeueButton
        public FrontButton(QueuePanel aQueuePanel) {
            super("Front");
            _queuePanel = aQueuePanel;
            _queue = aQueuePanel.getQueue();
            this.addActionListener(new FrontButtonListener());
        private class FrontButtonListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                SmartRectangle rectangle = _queue.front();    // remove item from queue
                SmartRectangle displayRect = _queuePanel.getDisplayFrontRect();
                if (rectangle != null)
                    displayRect.setColor(rectangle.getColor());
                _queuePanel.repaint();
    QueueApp
    import javax.swing.*;
    import java.awt.*;
    public class QueueApp extends JFrame
         * Constructor for objects of class QueueApp
        public QueueApp(String title)
            super(title);
            this.setSize(600,450);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            QueuePanel queuePanel = new QueuePanel();
            javax.swing.JPanel buttonPanel = new JPanel(new FlowLayout());
            buttonPanel.add(new EnqueueButton(queuePanel));
            buttonPanel.add(new DequeueButton(queuePanel));
            buttonPanel.add(new FrontButton(queuePanel));
            this.add(queuePanel, BorderLayout.CENTER);
            this.add(buttonPanel, BorderLayout.SOUTH);
            this.setVisible(true);     
        public static void main (String [] args)
            QueueApp app = new QueueApp("Queues at work: Object Oriented implementation.");
    QueuePanel
    import javax.swing.*;
    import java.awt.*;
    public class QueuePanel extends javax.swing.JPanel {
        // instance variables
        private Queue<SmartRectangle> _queue;
        private SmartRectangle _frontRect;
         * Constructor for objects of class QueuePanel
        public QueuePanel() {
            super();
            _queue = new CircularQueue<SmartRectangle>();
            _frontRect = new SmartRectangle(50,50,20,20,Color.WHITE, this);
       public Queue<SmartRectangle> getQueue() {
           return _queue;
       public SmartRectangle getDisplayFrontRect() {
           return _frontRect;
       public void paintComponent(Graphics aBrush) {
           super.paintComponent(aBrush);
           Graphics2D aBetterBrush = (Graphics2D) aBrush;
           Queue<SmartRectangle> tempQueue = new CircularQueue<SmartRectangle>();
           if (_frontRect.getColor() != this.getBackground())
               _frontRect.fill(aBetterBrush);
           while (!_queue.isEmpty()) {       // remove and display contents
               SmartRectangle rectangle = _queue.dequeue();
               rectangle.fill(aBetterBrush);
               tempQueue.enqueue(rectangle);
           while (!tempQueue.isEmpty()) {    // put contents back into _queue
               _queue.enqueue(tempQueue.dequeue());
           _frontRect.setColor(this.getBackground());
    SmartNode
    public abstract class SmartNode<ElementType> {
         public abstract boolean isEmpty();
         public abstract SmartNode<ElementType> dequeue(DataHolder<ElementType> aHolder);
         public abstract void front(DataHolder<ElementType> aHolder);
         public void enqueue(ElementType anItem){}
         public void setNext(SmartNode<ElementType> aNode) {
         }  // override as needed
         public void setPrev(SmartNode<ElementType> aNode) {
         }  // override as needed
    SmartRectangle
    import javax.swing.*;
    import java.awt.*;
    import java.awt.geom.*;
    public class SmartRectangle extends Rectangle2D.Double {
        // instance variables
        private JPanel _panel;
        private Color _color;
         * Constructor for objects of class SmartRectangle
        public SmartRectangle(int x, int y, int aWidth, int aHeight, Color aColor,
                              JPanel aPanel) {
            super(x, y, aWidth, aHeight);
            _panel = aPanel;
            _color = aColor;
        public void setLocation (int x, int y) {
            this.setFrame(x, y, this.getWidth(), this.getHeight());
        public Color getColor() {
            return _color;
        public void setColor(Color aColor) {
            _color = aColor;
        public void fill(Graphics2D aPaintBrush) {
            Color savedColor = aPaintBrush.getColor();
            aPaintBrush.setColor(_color);
            aPaintBrush.fill(this);
            aPaintBrush.setColor(savedColor);
    }

    > Yea I think I understand the concept of it, but I
    dont know what the code is supposed to look like.
    Showing you what the code is supposed to look like would be effectively giving you the answer, which kind of defeats the purpose of "extra credit". Have you tried anything so far? Post what you've got, and we can give you hints on how to work through it. I thought some of the descriptions here were very explicit hints, but if you need some additional guidance, let us know your specific questions (other than "show me the code").
    Good luck!
    ~

  • Is it possible to implement or represent a Linked List in LabVIEW?

    Linked lists are a useful way to store and retrieve data and I am wondering if it is possible to create or acheive the same objective of a linked list in LabVIEW.

    A linked list is a collection of nodes, each node has data and a link (or pointer) to the location of the next node.
    In LabVIEW we can create a collection of nodes as an array of clusters. One element of the cluster will be our data, and the other will be an integer pointer to the location in the array, of our next node.
    In, fact you can go crazy and represent a LabVIEW Hierarchy in a similar fasion (a tree structure). Now, each cluster will have data about the VI (its Name, attributes, etc), an array of integers that point the the locations of calling VIs, and an array of integers that point the the locations of subVIs.
    You will, of course also need some tools for sorting your lists/trees and performing useful operations... lot's of fun!
    Good luck
    Jim

  • Implementing TRIE using linked lists

    Node InsertNode(string name, Node root)
    int index = 1;
    string key;
    Node currentNode = root;
    while (index <= name.Length)
    key = name[index - 1].ToString();
    Node resultNode = currentNode.Children.GetNodeByKey(key);
    if (resultNode == null)
    Node newNode = new Node(key, name.Substring(0, index));
    if (index == name.Length)
    newNode.IsTerminal = true;
    currentNode.Children.Add(newNode);
    currentNode = newNode;
    else
    currentNode = resultNode;
    index++;
    return root;
    i want to use linked lists. i dont no what nodes are.like basically how do i use linked lists in the place of nodes in this code?
    thanx

    http://www.codeproject.com/KB/recipes/PhoneDirectory.aspx?display=Print <= code tags?
    coherent questions?
    class LinkedListNode {
    private LinkedListNode next;
    private Object data;
    public void insertAfter(Object data) {
    LinkedListNode newNode = new LinkedListNode();
    newNode.data = data;
    newNode.next = next;
    this.next = newNode;
    this is ur typical insert method for a linkedlistnode. you're saying nodes do the dirty work. how do connect this code with the one i posted in my previous msg? where do i get NODE from. What is this class.

Maybe you are looking for

  • Blue screen appears on Windows HP G56. ***STOP: 0x000000F4

    Blue screen appears at random times ...  Product name: HP G56 Notebook PC Product number: XP267EA#ABU Message reads:  If problems continue, disable or remove any newly installed hardware or software. Disable BIOS memory options such as caching or sha

  • Using BATCH-EXPORT on subclips vs MM to create independent media files

    I've been capturing full HDV tapes with the DV Start/Stop Detection turned on and everything has worked just fine - until now. I'm now encountering a problem w FCP "Searching for Media" on roughly 25% of my clips DURING capture, and in the process, l

  • APD issue, Data not showing correctly in APD.

    Hi All, Please guys help me with this APD issue that I am facing. There is an APD created whose target is a file and with one routine. Here the purpose of the routine was mostly just to sequence the fields the way I want them, and only to show certai

  • Is it possible to play albums consecutively?

    I have a series of audio books telling a continuous story, which I originally ripped in Media Player when I had a different MP3 player. At that time it seemed easier to rename the CD tracks so that the several CD's of one story played as one long alb

  • How to download / install ARD 3.7.2 for Yosemite?

    I was running Yosemite Beta. I had 10.10 beta 6 installed on my MacPro tower (aka the shiny black trashcan). Downloaded and installed the 10.10 final version, and all appeared well. ARD was - and is - working. To be clear : ARD Admin 3.7.2 (372a19) w