Linked List inside a class

I would like to define a LinkedList of feet in my table class.
I would like the ability to create 1000 tables some with 20 legs all different shapes and colours ect. ect. This is just an example (i'm not really creating tables) :) but its what i could think of at the time!
public class table {
  String colour;
  String wood;
  LinkedList feet;
  private class feet {
    String colour;
    String ripples;
    feet(String colour, String ripples)
      this.colour = colour;
      this.ripples = ripples;
}This doesn't seem to work, how could i define it? Or should i just create a LinkedList feet; and then just through then create a new feet object and add it to the linkedlist?

but its what i could think of at the time!You must've been smoking some weird, funny cigarets at that time ;-)
kind regards,
ps. keep the dukes or donate 'em to the poor.

Similar Messages

  • Recursion using a linked list

    I am confused at how to make a linked list using recursion. I've been looking at the syntax and examples from the web for the past couple hours, but all seem to be based on an empty .java file. I need to put it in my code somehow. here's the code segment:
    public static boolean RecursiveTest (String s, int start, Node n) {
    // The linked list
    Node<char> bracket = new Node<char>();
    int size = s.length();
    char v = s.charAt(start);
    //String sElement = parens.top();
    boolean isGood = true;
    // ending "ifs"
    if (size == 0) { System.out.println("empty string");  return false; }
    if (start == size) return isGood;
    if (s.charAt(start) == '(' || s.charAt(start) == '[' ||
              s.charAt(start)== '{') {
    v.Push(sChar);
    System.out.println(sChar);
    return RecursiveTest(start+1, s.charAt(start));
    else if (sChar.equals(")") && sElement.equals("(")) {
    parens.Pop();
    System.out.println(sChar);
    return RecursiveTest(start+1);
    else if (sChar.equals("]") && sElement.equals("[")) {
    parens.Pop();
    System.out.println(sChar);
    return RecursiveTest(start+1);
    else if (sChar.equals("}") && sElement.equals("{")) {
    parens.Pop();
    System.out.println(sChar);
    return RecursiveTest(start+1);
    else if (sChar.equals(")") && !sElement.equals("(")) {
    System.out.println("bad");
    isGood = false;
    return isGood;
    else if (sChar.equals("]") && !sElement.equals("[")) {
    System.out.println("bad");
    isGood = false;
    return isGood;
    else if (sChar.equals("}") && !sElement.equals("{")) {
    System.out.println("bad");
    isGood = false;
    return isGood;
    else return RecursiveTest(start+1);
    } // end of RecursiveTest
    I'm passing a string, 0, and a new node (i dunno about the last one there), from an above main class.
    This code is wrong, i know, but it's all I got done so far. How would I be able to make a linked list inside this method?

    No one knows how to do a linked list inside a recursive method?Yes we do, but you have to realize that a list (whether it be a linked list
    or an array list or whatever) has nothing to do with recursion per se.
    If that list has to keep track of some state it certainly mustn't be created
    within that recursive method as a local variable. And (see my previous
    reply), what do you need recursion for? Counting and pairing brackets
    can easily be done using an iterative method where the list keeps track
    of the last seen left bracket (of any type).
    kind regards,
    Jos

  • Putting a class of objects in a Linked List?

    Hi,
    I copied a program from a book and I want to edit it and put studentRecord class in the Linked List. I've tried to play about with datum, but everything I try doesn't work. Can someone help me out? How could I put studentRecord in the LinkedList?
    import java.io.*;
    class IO
         static BufferedReader keyboard = new
              BufferedReader(new InputStreamReader(System.in));
         static PrintWriter screen = new PrintWriter(System.out, true);
    class studentRecord
         private String name;
         private int IDNumber;
    class LinkedList
         class Node
              protected Object datum;
              protected Node link;
              public Node() {}
              public Node(Object item, Node pointer)
                   datum = item;
                   link = pointer;
         private Node head;
         private Node tail;
         private Node temporary;
         private int nodeCount = 0;
         //constructor
         public LinkedList()
              head = null;
              tail = null;
              temporary = null;
         //method to insert an object into the linked list
         public void insert(Object datum)
              if (head == null) // list empty
                   head = new Node(datum, head);
                   tail = head;
              else
                   temporary = new Node(datum, temporary);
                   tail.link = temporary;
                   tail = temporary;
                   temporary = null;
              nodeCount++;
    Full program can be found: http://dil3mma.tripod.com/LinkedList.txt
    Thanks in advance.

    Hi jverd,
    Thanks for replying. I've tried to change the program liked you said but there is 1 error I can't seem to fix(Im sure there are more tho). The error is "cannot resolve symbol" I typed in caps the line it happens on so it's easy to see. Any idea what it could be? Is it cause I'm comparing a String with Object?
    import java.io.*;
    class IO
         static BufferedReader keyboard = new
              BufferedReader(new InputStreamReader(System.in));
         static PrintWriter screen = new PrintWriter(System.out, true);
    class sRecord
         private String name;
         private int IDNumber;
    class LinkedList
         class Node
              protected sRecord datum;
              protected Node link;
              public Node() {}
              public Node(sRecord item, Node pointer)
                   datum = item;
                   link = pointer;
         private Node head;
         private Node tail;
         private Node temporary;
         private int nodeCount = 0;
         //constructor
         public LinkedList()
              head = null;
              tail = null;
              temporary = null;
         //method to insert an object into the linked list
         public void insert(sRecord datum)
              if (head == null) // list empty
                   head = new Node(datum, head);
                   tail = head;
              else
                   temporary = new Node(datum, temporary);
                   tail.link = temporary;
                   tail = temporary;
                   temporary = null;
              nodeCount++;
         //method to delete an object from the linked list
         public boolean delete(Object scrap)
              Node previous = head;
              //for every node in the linked list
              for (Node current = head; current != null; current = current.link)
                   //node to be deleted is at the head of the list
                   if (current.datum.equals(scrap) && previous == current)
                        head = current.link;
                        if (head == null) tail = null;
                        nodeCount--;
                        return true;
                   //node to be deleted is after the first node and before the last
                   else if (current.datum.equals(scrap) && (current.link != null))
                        previous.link = current.link;
                        nodeCount--;
                        return true;
                   //node to be deleted is at the ned of list
                   else if (current.datum.equals(scrap) && (current.link == null))
                        tail = previous;
                        previous.link = null;
                        nodeCount--;
                        return true;
                   previous = current;
              return false;
         //method to display the contents of a linked list
         public void displayList()
              Node temporary = head;
              if (head == null)
                   IO.screen.println("linked list is empty");
                   return;
              while (temporary != null)
                   IO.screen.println(temporary.datum);
                   temporary = temporary.link;
         //method to return true if the linked list is empty
         public boolean isEmpty()
              return (nodeCount == 0);
         //method to return the number of nodes in the linked list
         public int nodes()
              return nodeCount;
         //method to display a menu to insert data into the linked list
         static private char menu()
              char response = '\u0000';
              IO.screen.println("Do you want to ");
              IO.screen.print("nsert, [D]elete, [L]ist, [E]xit? ");
              IO.screen.flush();
              boolean done=false;
              do
                   try
                        String data = IO.keyboard.readLine();
                        response = Character.toUpperCase(data.charAt(0));
                        done = true;
                   catch (Exception e)
                        IO.screen.println("Please input a single character I, D, L or E");
              } while (! done);
              return response;
         static public void main(String[] args) throws IOException
              LinkedList list = new LinkedList();
              String datum;
              char choice;
              //get information from menu
              choice = menu();
              for (;;)
                   //Menu
                   switch (choice)
                        case 'I' :
                             IO.screen.println("type quit to finish input");
                             IO.screen.print("Enter a word ");
                             IO.screen.flush();
                             datum = IO.keyboard.readLine();
                             while (! datum.equals("quit"))
    THE ERROR HAPPENS HERE ON THIS LINE          list.insert(datum.name);
                                  IO.screen.print("Enter another word");
                                  IO.screen.flush();
                                  datum = IO.keyboard.readLine();
                             break;
                   case 'D' :
                        //if list is empty deletion not possible
                        if (list.isEmpty())
                             IO.screen.println("linked list is empty");
                             break;
                        IO.screen.println("type quit to finish input");
                        IO.screen.print("Delete? ");
                        IO.screen.flush();
                        datum = IO.keyboard.readLine();
                        while (! datum.equals("quit"))
                             if (list.delete(datum))
                                  IO.screen.println(datum+" was scrapped!");
                             //if list is empty deletion is not possible
                             if (list.isEmpty())
                                  IO.screen.println("linked list is empty");
                                  break;
                             IO.screen.print("Delete? ");
                             IO.screen.flush();
                             datum = IO.keyboard.readLine();
                        break;
                   case 'L' :
                        list.displayList();
                        IO.screen.println("number of nodes " + list.nodes());
                        break;
                   case 'E' : System.exit(0);
              //get information from menu
              choice = menu();

  • Trouble importing third party classes & using linked list in j2me

    Hi!
    I need to use the linked list data structure in a j2me application im developing. Al long as I know, it is not included in standard libraries.
    I found the "workaround", the substitution in Jade Laepaddon. This is actually a set of classes in a directory.
    I know this is extremely dumb, but I have no luck impotring these classes in my project.
    Im using the WTK2.0 to compile and execute the application, but I don't have an Idea how to add a directory in the CLASSPATH.
    So, the actual question should be: how to include a directory of files, so that it can be imported with:
    import dirName.*;
    Thanks!

    Tha import problem is solved, but I'm still not able to use the LinkedList class. In the jade/util/leap there is a LinkedList.java file, but I get an error :
    /home/mile/WTK2.0/apps/myGame/tmplib/jade.jar(jade/util/leap/LinkedList.java):48: class LinkedList is public, should be declared in a file named LinkedList.java
    (source unavailable)
    /home/mile/WTK2.0/apps/myGame/tmplib/jade.jar(jade/util/leap/LinkedList.java):48: cannot resolve symbol
    symbol : class List
    location: class jade.util.leap.LinkedList
    (source unavailable)
    /home/mile/WTK2.0/apps/myGame/tmplib/jade.jar(jade/util/leap/LinkedList.java):48: cannot resolve symbol
    symbol : class Serializable
    location: class jade.util.leap.LinkedList
    (source unavailable)
    /home/mile/WTK2.0/apps/myGame/tmplib/jade.jar(jade/util/leap/Iterator.java):41: class Iterator is public, should be declared in a file named Iterator.java
    (source unavailable)
    when initialising an LinkedList type object.

  • 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();

  • Help abstract classes linked list

    I have a base abstract class Vegetable which is basically Node for a linkedlist
    The base class Vegetable has a few abstract methods Pumpkin, Carrot, Potato basically extends Vegetable
    Another class called VegetableCollection
    basically in VegetableCollection
    can this be done if the objects are different types eg Pumpkin, potato, Carrot?
    public void add(Vegetable addObject)
    head = new Vegetable(addObject);
    }

    I have a base abstract class Vegetable which is basically Node for a linkedlist
    The base class Vegetable has a few abstract methods Pumpkin, Carrot, PotatoYou probably wouldn't have abstract methods with those names. Abstract methods are methods that you will need to define in every subclass. And a subclass called Pumpkin probably won't have meaningful definitions for methods called Carrot and Potato.
    can this be done if the objects are different types eg Pumpkin, potato, Carrot?
    public void add(Vegetable addObject)
    head = new Vegetable(addObject);
    }Here is an example of "polymorphism" at work:
    import java.util.*;
    abstract class Vegetable
      public abstract void identify();
    class Carrot extends Vegetable
      public void identify()
        System.out.println("I'm a Carrot.");
    class Pumpkin extends Vegetable
      public void identify()
        System.out.println("I'm a Pumpkin.");
    public class Test
      public static void main(String args[])
        LinkedList<Vegetable> myVegetables = new LinkedList<Vegetable>();
        myVegetables.add(new Carrot());
        myVegetables.add(new Pumpkin());
        Iterator<Vegetable> i = myVegetables.iterator();
        Vegetable v = null;
        while(i.hasNext())
          v = i.next();
          v.identify();
    output:
    I'm a Carrot.
    I'm a Pumpkin.To get polymorphism to work, you need to:
    1) Define a base class with a method that you want in all the subclasses.
    2) Override the method in the subclasses so that it does what's necessary for that subclass.
    3) Store the subclass objects in a variable(or collection) whose type is the base class.
    4) Call the method on the base type variable. Then through the magic of polymorphism, java will examine the actual object stored in the base type variable to determine what subclass it is, and then java will call the version of the method in that subclass.
    As the previous poster mentioned, you need to define a class called Node, which has head, previous, and next members. Your Node class will also have a member variable called veggie, which will be of type Vegetable. Then you can assign a Carrot, Pumpkin, or Potato object to that member variable.
    I assume this is an exercise where you have to create your own linked list. Otherwise, you can use the linked lists provided by java, which are very easy to use.

  • How to use methods when objects stored in a linked list?

    Hi friend:
    I stored a series of objects of certain class inside a linked list. When I get one of them out of the list, I want to use the instance method associated with this object. However, the complier only allow me to treat this object as general object, ( of Object Class), as a result I can't use instance methods which are associated with this object. Can someone tell me how to use the methods associated with the objects which are stored inside a linked list?
    Here is my code:
    import java.util.*;
    public class QueueW
         LinkedList qList;
         public QueueW(Collection s) //Constructor of QuequW Class
              qList = new LinkedList(s); //Declare an object linked list
         public void addWaiting(WaitingList w)
         boolean result = qList.isEmpty(); //true if list contains no elements
              if (result)
              qList.addFirst(w);
              else
              qList.add(w);
         public int printCid()
         Object d = qList.getFirst(); // the complier doesn't allow me to treat d as a object of waitingList class
              int n = d.getCid(); // so I use "Object d"
         return n; // yet object can't use getCid() method, so I got error in "int n = d.getCid()"
         public void removeWaiting(WaitingList w)
         qList.removeFirst();
    class WaitingList
    int cusmNo;
    String cusmName;
    int cid;
    private static int id_count = 0;
         /* constructor */
         public WaitingList(int c, String cN)
         cusmNo = c;
         cusmName = cN;
         cid = ++id_count;
         public int getCid() //this is the method I want to use
         return cid;

    Use casting. In other words, cat the object taken from the collection to the correct type and call your method.
       HashMap map = /* ... */;
       map.put(someKey, myObject);
       ((MyClass)(map.get(someKey)).myMethod();Chuck

  • Recursion:returning the largest value in a linked list

    import java.io.*;
    import java.util.*;
    class Node{
         int num;
         Node next;
         Node(int n){
              num = n;
              next = null;
    class RecursivePrint{
         public static void main(String[] args){
              Node np, last;
              Node top = null;
              last = null;
              for(int i = 1; i <11; i++){
                   np = new Node(i);
                   if(top==null)top = np;
                        else
                   last.next = np;
                   last = np;
              int x =Largest(top);
             System.out.println("large is "+ x);
         }//end main
         public static int Largest(Node top){
              int large = 0;
              if(top==null){
                   return 0;
                   while(top!=null){
               if(top.num > large){
                   large = top.num;
                   //top = top.next;
              Largest(top.next);     
         }//while
         return large;
    }//end class
    I am trying to return the largest value in a linked list (10) in this case.  when I do it withour recurrsion it works ok, but when I try it with recurrsion it dies.  The logic seems ok to me, cannot figure why it dies.

    chetah wrote:
    public static int Largest(Node top){
              int large = 0;
              if(top==null){
                   return 0;
              if(top.num > large){
                   large = top.num;
                   //top = top.next;
                   Largest(top.next);
         return large;
    Initially I had the above, it return only 1 that was the reason for puting the loop.You don't seem to understand recursion or variable scope.
    int large = 0;large is a different variable inside each instance of the method.
    So when you get back up to the value 1 from the recursive calls its just comparing 1 to 0
    Here's a solution...
         public static int Largest(Node top){
              if(top.next != null){
                   if(Largest(top.next) > top.num)
                        return Largest(top.next);}
              return top.num;
         }

  • Values of data  in a linked-list

    hello.
    i declare a small linked list of elemets (about 10), everything is fine and dandy but i need to assign an int value to every one of those elements as a counter whenever a certain action is performed on the element in the list.
    LinkedList mylist = new Linkedlist();
    int value=0;
    //i need to assign a unique int value to every element in the list as a counter to keep track of how many times [whatever element] is accessed, moved around, ect.
    is this possible?

    If your linked list contains a specific type of object, add a counter to it. This may mean extending whatever the class the element is.
    If you want to do theis generically, you are probably going to have to extend LinkedList and inside that class encapsulate another collection (maybe a linked list). The encapsulated collection will contain the set of counters. You will have to override all of LinkedLists methods so that you can maintain the counters.

  • Linked lists problem -- help needed

    Hello again. I've got yet another problem in my C++ course that stems from my use of a Mac instead of Windows. I'm going to install Parallels so I can get Windows on my MacBook and install Visual Studio this week so that I don't have to deal with these discrepancies anymore, but in the meanwhile, I'm having a problem here that I don't know how to resolve. To be clear, I've spent a lot of time trying to work this out myself, so I'm not just throwing this up here to have you guys do the work for me -- I'm really stuck here, and am coming here as a last resort, so I'll be very, very appreciative for any help that anyone can offer.
    In my C++ course, we are on a chapter about linked lists, and the professor has given us a template to make the linked lists work. It comes in three files (a header, a source file, and a main source file). I've made some adjustments -- the original files the professor provided brought up 36 errors and a handful of warnings, but I altered the #include directives and got it down to 2 errors. The problematic part of the code (the part that contains the two errors) is in one of the function definitions, print_list(), in the source file. That function definition is shown below, and I've marked the two statements that have the errors using comments that say exactly what the errors say in my Xcode window under those two statements. If you want to see the entire template, I've pasted the full code from all three files at the bottom of this post, but for now, here is the function definition (in the source file) that contains the part of the code with the errors:
    void LinkedList::printlist( )
    // good for only a few nodes in a list
    if(isEmpty() == 1)
    cout << "No nodes to display" << endl;
    return;
    for(CURSOR = FRONT_ptr; CURSOR; CURSOR = CURSOR-> link)
    { cout << setw(8) << CURSOR->name; } cout << endl; // error: 'setw' was not declared in this scope
    for(CURSOR = FRONT_ptr; CURSOR; CURSOR = CURSOR-> link)
    { cout << setw(8) << CURSOR->test_grade; } cout << endl; // error: 'setw' was not declared in this scope
    As you can see, the problem is with the two statements that contain the 'setw' function. Can anyone help me figure out how to get this template working and get by these two errors? I don't know enough about linked lists to know what I can and can't mess with here to get it working. The professor recommended that I try using 'printf' instead of 'cout' for those two statements, but I don't know how to achieve the same effect (how to do whatever 'setw' does) using 'printf'. Can anyone please help me get this template working? Thank you very, very much.
    For reference, here is the full code from all three files that make up the template:
    linkedlist.h (header file):
    #ifndef LINKED_LINKED_H
    #define LINKED_LINKED_H
    struct NODE
    string name;
    int test_grade;
    NODE * link;
    class Linked_List
    public:
    Linked_List();
    void insert(string n, int score);
    void remove(string target);
    void print_list();
    private:
    bool isEmpty();
    NODE *FRONT_ptr, *REAR_ptr, *CURSOR, *INSERT, *PREVIOUS_ptr;
    #endif
    linkedlist.cpp (source file):
    #include <iostream>
    using namespace std;
    #include "linkedlist.h"
    LinkedList::LinkedList()
    FRONT_ptr = NULL;
    REAR_ptr = NULL;
    PREVIOUS_ptr = NULL;
    CURSOR = NULL;
    void Linked_List::insert(string n, int score)
    INSERT = new NODE;
    if(isEmpty()) // first item in List
    // collect information into INSERT NODE
    INSERT-> name = n;
    // must use strcpy to assign strings
    INSERT -> test_grade = score;
    INSERT -> link = NULL;
    FRONT_ptr = INSERT;
    REAR_ptr = INSERT;
    else // else what?? When would this happen??
    // collect information into INSERT NODE
    INSERT-> name = n; // must use strcpy to assign strings
    INSERT -> test_grade = score;
    REAR_ptr -> link = INSERT;
    INSERT -> link = NULL;
    REAR_ptr = INSERT;
    void LinkedList::printlist( )
    // good for only a few nodes in a list
    if(isEmpty() == 1)
    cout << "No nodes to display" << endl;
    return;
    for(CURSOR = FRONT_ptr; CURSOR; CURSOR = CURSOR-> link)
    { cout << setw(8) << CURSOR->name; } cout << endl; // error: 'setw' was not declared in this scope
    for(CURSOR = FRONT_ptr; CURSOR; CURSOR = CURSOR-> link)
    { cout << setw(8) << CURSOR->test_grade; } cout << endl; // error: 'setw' was not declared in this scope
    void Linked_List::remove(string target)
    // 3 possible places that NODES can be removed from in the Linked List
    // FRONT
    // MIDDLE
    // REAR
    // all 3 condition need to be covered and coded
    // use Trasversing to find TARGET
    PREVIOUS_ptr = NULL;
    for(CURSOR = FRONT_ptr; CURSOR; CURSOR = CURSOR-> link)
    if(CURSOR->name == target) // match
    { break; } // function will still continue, CURSOR will
    // mark NODE to be removed
    else
    { PREVIOUS_ptr = CURSOR; } // PREVIOUS marks what NODE CURSOR is marking
    // JUST before CURSOR is about to move to the next NODE
    if(CURSOR == NULL) // never found a match
    { return; }
    else
    // check each condition FRONT, REAR and MIDDLE
    if(CURSOR == FRONT_ptr)
    // TARGET node was the first in the list
    FRONT_ptr = FRONT_ptr -> link; // moves FRONT_ptr up one node
    delete CURSOR; // deletes and return NODE back to free memory!!!
    return;
    }// why no need for PREVIOUS??
    else if (CURSOR == REAR_ptr) // TARGET node was the last in the list
    { // will need PREVIOUS for this one
    PREVIOUS_ptr -> link = NULL; // since this node will become the last in the list
    REAR_ptr = PREVIOUS_ptr; // = REAR_ptr; // moves REAR_ptr into correct position in list
    delete CURSOR; // deletes and return NODE back to free memory!!!
    return;
    else // TARGET node was the middle of the list
    { // will need PREVIOUS also for this one
    PREVIOUS_ptr -> link = CURSOR-> link; // moves PREV nodes' link to point where CURSOR nodes' points
    delete CURSOR; // deletes and return NODE back to free memory!!!
    return;
    bool Linked_List::isEmpty()
    if ((FRONT_ptr == NULL) && (REAR_ptr == NULL))
    { return true; }
    else
    { return false;}
    llmain.cpp (main source file):
    #include <iostream>
    #include <string>
    #include <iomanip>
    using namespace std;
    #include "linkedlist.h"
    int main()
    Linked_List one;
    one.insert("Angela", 261);
    one.insert("Jack", 20);
    one.insert("Peter", 120);
    one.insert("Chris", 270);
    one.print_list();
    one.remove("Jack");
    one.print_list();
    one.remove("Angela");
    one.print_list();
    one.remove("Chris");
    one.print_list();
    return 0;

    setw is the equivalent of the field width value in printf. In your code, the printf version would look like:
    printf("%8s", CURSOR->name.c_str());
    I much prefer printf over any I/O formatting in C++. See the printf man page for more information. I recommend using Bwana: http://www.bruji.com/bwana/
    I do think it is a good idea to verify your code on the platform it will be tested against. That means Visual Studio. However, you don't want to use Visual Studio. As you have found out, it gets people into too many bad habits. Linux is much the same way. Both development platforms are designed to build anything, whether or not it is syntactically correct. Both GNU and Microsoft have a long history of changing the language standards just to suit themselves.
    I don't know what level you are in the class, but I have a few tips for you. I'll phrase them so that they answers are a good exercise for the student
    * Look into const-correctness.
    * You don't need to compare a bool to 1. You can just use bool. Plus, any integer or pointer type has an implicit cast to bool.
    * Don't reuse your CURSOR pointer as a temporary index. Create a new pointer inside the for loop.
    * In C++, a struct is the same thing as a class, with all of its members public by default. You can create constructors and member functions in a struct.
    * Optimize your function arguments. Pass by const reference instead of by copy. You will need to use pass by copy at a later date, but don't worry about that now.
    * Look into initializer lists.
    * In C++ NULL and 0 are always the same.
    * Return the result of an expression instead of true or false. Technically this isn't officially Return Value Optimization, but it is a good habit.
    Of course, get it running first, then make it fancy.

  • Help on Linked List

    Hey people, i need a small help on my linked list.
    Ok, what i'm trying to do is have a search function with a linked list using strings. First i will have a string, i will then compute the ASCII value for that and take MOD 71 lets say. For example, a string has an ASCII value of 216, MOD 71 of this gives me 3. I will then have an array of 71, and each array will point to a linked list. There will be as many linked list as there are of arrays (71). I will then store this string at index [3] in the linked list in which the array points to.
    My problem for now is, how do i for example create 71 linked list? So far i can create only 1. To create another is easy, but if i have 71 the code will be too much. Is there an iterator i could use that easily creates 71? Sorry about this, i'm not really good with linked list with Java. Anyway, here is what i have now :).
    public class MyLinkedListElement {   
            String string;
            MyLinkedListElement next;
            public MyLinkedListElement(String s) {   
                string = s;
                next = null;   
            public MyLinkedListElement getNext() {
                return next;       
            public String getValue() {
                return string;
    public class MyLinkedList {
        public static MyLinkedListElement head;
        public MyLinkedList() {   
            head = null;
       public static void addToHead(String s) {
            MyLinkedListElement a = new MyLinkedListElement(s);
            if (head == null) {
                head = a;
            } else {
                a.next = head;
                head = a;       
        public static void main(String[] args) {
              String[] arr = {"Bubble", "Angie", "Bob", "Bubble", "Adam"};
              for (int i = 0; i < arr.length; i++) {
                          addToHead(arr);
    MyLinkedListElement current = head;
    while (current != null) {
    System.out.println(current.getValue());
    current = current.next;
    }I can have an array of strings and easily add them to a linked list.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    I am very confused now, i just need to store a string value inside an array of linked list. But i can't somehow do it. I am very close, i can store the value in a linked list but the array of linked list, this is what i have.
    public class MyLinkedListElement {   
            String string;
            MyLinkedListElement next;
            public MyLinkedListElement(String s) {   
                string = s;
                next = null;   
            public MyLinkedListElement getNext() {
                return next;       
            public String getValue() {
                return string;
    public class MyLinkedList {
        public MyLinkedListElement head;
        public MyLinkedList() {   
              head = null;
        public void addToHead(String s) {
             MyLinkedListElement  a = new MyLinkedListElement(s);
             MyLinkedList[] arrayOfLinkedLists = new MyLinkedList[71];
             for(int i = 0; i < arrayOfLinkedLists.length; i++) {
                 arrayOfLinkedLists[i] = new MyLinkedList();
             if (head == null) {    
                 head = a;
             } else {
                 a.next = head;
                 head = a;       
        public void print(MyLinkedListElement current) {
              while (current  != null) {
                    System.out.println(current.getValue());
                    current = current.next;
        public static void main(String[] args) {
              String[] arr = {"Bubble", "Angie", "Bob", "Bubble", "Adam"};
              MyLinkedList listInstance = new MyLinkedList();
              for (int i = 0; i < arr.length; i++) {
                    listInstance.addToHead(arr);
    MyLinkedListElement current = listInstance.head;
    listInstance.print(current);

  • Linked List

    Hello
    I got a problem trying to store arrays in a linked list. i need to store 3 numbers in the array(eg a[0], a[1], a[2]) in a link list and another 3 in another and so on. (dnt have to use arrays but i used it to store the 3 number in one linked list)
    when i use arrays to store em it says cants store int cos my links list stores objects! i cant convert the numbers to object cos then i need to search for the particular set of numbers from the link list.
    if some one could help me by explaing wat i could do i will be gratefull
    thanks!!!

    Yes, as danperkins suggests you can insert groups of three int[] into your list ...and then as your search through the list, pull each group of three ints back out of each list node and analyze them on the spot to see if they are equal.
    What I was suggesting is to encapsulate your three ints into a class that becomes an entity called, say ...ThreeInts. Then, you could add the functionality inside this object to determine if it was equal to another object of the same type. Same thing as danperkins suggestion, except one requires external routines to process each node and the other (mine) uses an object that knows how to process itself.
    This is a fundamental facet of OOP programming ...representing data in objects that know how to store their values ...know how to express themselves ...know how to order and compare themselves ...etc, etc, etc.
    The way I see it, I have given you the structures required to complete your task ...you just have to operate on them and incorporate them into your code. If you don't see how to do this, then I don't really know what else to suggest ...sorry.
    semi - psuedocode created from what you have so far might be as follows.
    // Insert ThreeInts objects into linked list...
    // Where array is original array of 120 ints...
    for (int k=0, k<array.length; k++) {
      if( (k%3)==0 && k!=0 ) {
        list.add(new ThreeInts(array[k-2],array[k-1],array[k]);
    // Search for specific ThreeInts objects in linked list...
    // i.e. "find an object in the list equal to the object ThreeInts(3,5,8)"
    ThreeInts found = searchList( new ThreeInts(3,5,8) );Basically, the ThreeInts object is a class that knows how to hold three integers ...knows how to give these three integers back to you ...and most importantly knows how to compare itself to another ThreeInts object and say "yes, I am the same" ...or "No, I am not the same". That is what MyCuteLittleClass will do ...you just have to change its name to ThreeInts. Beyond this, I don't know what else to say.

  • Add,Get,Remove in linked lists

    I need to be able to add, get and remove items from the linked list and I can't seem to be able to get any of it to work. Ignore the coments, that's just where I was experimenting with other ways of doing it. I keep getting an error from inside case1 of Menu. Any ideas appreciated.
    import cs1.Keyboard;
    import StaffMember;
    import Employee;
    import java.util.*;
    public class Staff
         LinkedList myList = new LinkedList();
         public Staff ()
              //StaffMember staffList = new StaffMember[1];
              //private Employee[]firm;
              //private int currentSize;
              //private int count;
              public static void main (String[] args)
                   Menu();
                   Employee[] staffList = new Employee[1];
                   for (int i=0; i<1; i++)
                        //staffList[i] = setNewEmployee();
                        //System.out.println (staffList); (NOT NEEDED)
                        //myList.add(staffList[i]);
                        //myList.size();
                        //myList.toArray();
                   for (int count=0; count<staffList.length; count++)
                        System.out.println (staffList[count]);
                        System.out.println ("- - - - - - - - - - - - - - - - -");
              public static int Menu()
                   System.out.println("To add a new staff member press 1");
                   System.out.println("To find a staff member press 2");
                   System.out.println("To remove a staff member press 3");
                   int choice = Keyboard.readInt();
                   int effect = choice;
                   switch(effect)
                        case 1:
                             System.out.println("Adding new staff member");
                             setNewEmployee();
                             myList.add(new Employee);
                             myList.toArray();
                             break;
                        case 2:
                             System.out.println("Finding staff member");
                             break;
                        case 3:
                             System.out.println("Removing staff member");
                             break;
                        default:
                             System.out.println("invalid entry!");
                   return choice;
              private static Employee setNewEmployee()
                   String name, address, phone;
                   int staffID;
                   System.out.print("Input ID: ");
                   staffID = Keyboard.readInt();
                   System.out.print("Input Name: ");
                   name = Keyboard.readString();
                   System.out.print("Input Address: ");
                   address = Keyboard.readString();
                   System.out.print("Input Phone: ");
                   phone = Keyboard.readString();
                   Employee s = new Employee(name, address, phone, staffID);
                   return s;

    This should get you going:
    case 1:
                          System.out.println("Adding new staff member");
    //                      setNewEmployee();  // this returns an object but there is nothing to store it in
                          myList.add(setNewEmployee);  // use the returned object as a direct argument
    //                      myList.toArray();  // this returns an array of objects but nothing to store the array in
                          break;As you continue by uncommenting the code in the other sections of your program, you will find similar type of erros.
    V.V.

  • Why am I doing this - in reference to Linked List Assignment

    So I have a programming assignment to do for class, and in it the instructor wants us to write our own class for LinkedList. Upon browsing the java library I found that there is a java.util.LinkedList class with appropriate methods already defined. Is my instructor crazy or just outdated, I can see the point in writing one, to better understand the Linked List, but the one in the library is probably better anyway.
    Is there a way to peek inside the code for java.util.LinkedList to at least get an idea of how I should start writing this class?
    Thank You.

    baftos wrote:
    datawerd wrote:
    So I have a programming assignment to do for class, and in it the instructor wants us to write our own class for LinkedList. Upon browsing the java library I found that there is a java.util.LinkedList class with appropriate methods already defined. Is my instructor crazy or just outdated, I can see the point in writing one, to better understand the Linked List, but the one in the library is probably better anyway.
    Is there a way to peek inside the code for java.util.LinkedList to at least get an idea of how I should start writing this class?Yes, there is a way and, unlike others, I admire your approach. It's so refreshing after seeing all the 'do my homework' krapp. I call this reasearch, not cheating. Go to your JDK directory and open src.zip.
    You will find there what you need. And by the way, peeking inside this zip would answer hundreds of questions,
    Whenever I don't quite know how to do something, I try to find a similar API class and just see how Sun does it.
    Edited by: baftos on Oct 16, 2007 10:46 PMYeah man, I'm with you on this one. I don't consider it cheating at all (given that you could find it on Wikipedia anyway), and I learn by example.
    Apache taught me how to make an LRU cache the other day. Thanks Apache!
    EDIT: To the OP: by the way, the LRU algorithm uses a modified linked list that I wouldn't have understood if i hadn't done my work in grade 12 / first year com-sci courses.
    Edited by: endasil on Oct 16, 2007 8:12 PM

  • New to java  -especially linked lists

    I�m trying to work with linked lists but not having much luck�
    Overall, the program must create a datastructure that will hold titles of articles. Up to 10 keywords can be added to each article and it must then be possible to search all of the titles for matches to the keyword.
    Currently I�m stuck in a for-loop � my linked list (articleList) is not accepted. Any help would be much appreciated. The following error occurs when I attempt to compile:
    SearchMachine.java:30: cannot resolve symbol
    symbol : variable articleList
    location: class SearchMachine
              for(ListIterator listiter = articleList.listIterator(); listiter.hasNext();)
    ^
    import java.util.*;
    class Document
         private String title;
         private String keywords [] = new String [10];
         private int last = 0;
         public Document (String _title)
              String title = _title;
         public void addKeyword(String kw)
              if(last < 9)
                   keywords [last]= kw;
                   last ++;
                   System.out.println("The keyword " + kw + " has now been added");
              else if (last == 9)
                   keywords [last]= kw;
                   System.out.println ("The document now has 10 keywords. No more can be added");
    class SearchMachine
         SearchMachine()
              LinkedList articleList = new LinkedList ();
              articleList.add (new Document ("Oracle 8 the new SQL programming"));
              articleList.add (new Document ("Java programming made easy"));
         public void print()
              for(ListIterator listiter = articleList.listIterator(); listiter.hasNext();)
                   System.out.println(listiter.next());
         public static void main (String [] args)
              SearchMachine search;     
              search = new SearchMachine();
              search.print();

    This is a basic scope issue. You declare the variable articleList inside the constructor block and thus it's visible only in the constructor block. The variable doesn't exist anywhere else but in SearchMachine() {...} The solution is to move the line "LinkedList articleList = new LinkedList();" three lines up, outside the constructor but inside the class definition, so that articleList becomes a member of the SearchMachine class.

Maybe you are looking for