Question repost: Add Methods in a Linked List.

Please excuse my reposting of this question. The previous question had a lot of unformatted code.
Here, I'll just have the two methods that I need help with. If more information is needed, I have it by the buttloads.
They are add methods for a List class:
  public boolean add(E o)
  Node newNode = new Node();
  newNode.data = o;
  if (first == null)
      first = last = newNode;
  else {
  last.next = newNode;
  } // end if
  size++;
  return true;
public void addLast(E o)
  Node newNode = new Node();
  newNode.data = o;
  newNode.previous = last;
  if (first == null)
      first = last = newNode;
  else {
  last.next = newNode;
   size++;
  }Can anybody help me with these? Duke points will be rewarded.

Once again: continue to ask for help in your original post. Include your up-to-date code and provide as much details as possible, such as error messages (copy and paste the entire message, do not paraphrase) or for incorrect behviour describe what is happening and what is supposed to happen.
Do this in your original post. I don't want to see another post here!

Similar Messages

  • How to add SharePoint 2013 Promoted link list view web part in page programatically with Tiles view using CSOM.

    How to add SharePoint 2013 Promoted link list view web part in page programatically with Tiles view using CSOM. I found that it can be
    done by using XsltListViewWebPart class but how can I use this one by using shraepoint client api.
    shiv

    Nice, can you point me to the solution please ?
    I'm  trying to do this but I get an error : 
    Web Part Error: Cannot complete this action. Please try again. Correlation ID: blablabla
    StackTrace:    at Microsoft.SharePoint.SPViewCollection.EnsureViewSchema(Boolean fullBlownSchema, Boolean bNeedInitallViews)     at Microsoft.SharePoint.SPList.GetView(Guid viewGuid)   
    All help really appreciated.

  • 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.

  • Using Collections.binarySearch on a Linked list

    hi all
    i want to use the Collections.binarySearch method on a linked list object to add items to it. These items are of type Entry (a class i have created).
    i have the following code:
    public void addEntry(Entry newEntry)
            int pos = Collections.binarySearch(entryList, newEntry);
            if (pos < 0)
                entryList.add(-(pos) -1, newEntry);
    [\CODE]
    where entryList is declared as:
    private List entryList = new LinkedList();
    This code compiles OK, but when i run it to add an Entry element to the linked list, i get a ClassCastException being thrown, and im not sure why.
    i can add one Entry object to the list ok, but it falls over when i try to add another. im trying to order my Entry objects by a field called 'surname', so the binarySearch finds the correct location in the list for the new entry and then it is added.
    any help on this would be appreciated
    cheers
    david                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    binarySearch doesn't work on a linked listSo untrue:Well, only mostly untrue. It still doesn't really do a binary search on your linked list
    From the javadoc
    'This method runs in log(n) time for a "random access" list (which provides near-constant-time positional access). If the specified list does not implement the RandomAccess and is large, this method will do an iterator-based binary search that performs O(n) link traversals and O(log n) element comparisons. '
    import java.util.*;
    public class Test {
    public static void main(String[] args) {
    List entryList = new LinkedList();
    entryList.add(new Integer(3));
    entryList.add(new Integer(5));
    entryList.add(new Integer(1));
    Collections.sort(entryList);
    System.out.println(Collections.binarySearch(entryList,
    new Integer(5)));
    }Compiles and runs without any problems

  • Help with copying contents of file to link list please

    Hi,
    Below is a snippet of code I am playing with. As you can see I have created a LinkList, I now need to copy the contents of a csv file in to that list. The file is several lines long and I need each line in the list.
    I know how to add to the list manually i.e.,
    list.add("First entry in list");
    Could someone help me out with this please.
    Many thanks.
    (***CODE***)
    private LinkedList list = new LinkedList();
         public LinkTest()
              // ** List content START **
              // Open the file today.csv
              File inFile = new File("C:\\today.csv");
         // Create a file stream, wrapping the file
         FileReader fileReader = new FileReader(inFile);
         // Create a second wrapper,
    BufferedReader bufReader = new BufferedReader(fileReader);
         // Read in the first line...
         String s;
         s = bufReader.readLine();
         list.add(s);
         StringTokenizer st = new StringTokenizer(s);
         while (st.hasMoreTokens())
    System.out.println(st.nextToken());
         // ** List content END **
         

    I looked at your code and I thought, what's the question for, it's already adding lines to the list. And then I looked again and had the same thought. The third time I looked I noticed you didn't code the loop that read all the lines from the file. Silly me, I thought your question had something to do with linked lists.
    Anyway, to answer your real question, which is how do you read all the lines from a text file:while ((s = bufReader.readLine()) != null) {
      // do something with the String s here
      // such as adding it to a linked list
    }

  • Addition in a linked list

    Hi,
    I want to add numbers in a linked list. For example when i pass in the string 123456789, i reverse it so that it appears as 987654321 in the linked list. If i add this to the string 954 which appears as 459 in the linked list, i am supposed to get 123457743 but i get 1743. How do i rectify this from my code.
    import java.util.LinkedList;
    import java.util.ListIterator;
    public class LargeInteger {
    /** Constructs a new LargeInteger object from the specified String.
    * The String parameter will contain the digits comprising the number
    * to be represented by this LargeInteger object. The number may be
    * either positive or negative, so be sure to check for a sign.
    * You should throw an IllegalArgumentException if the string which is
    * passed in does not contain a valid number. An invalid String would
    * be one which contains any character other than a digit (however the
    * first character may be a negative sign).
    * @param value A String representing the number to be represented.
    &nbs! p; * @throws IllegalArgumentException This exception is thrown if the
    * parameter doesn't contain a valid number.
    LinkedList digits = new LinkedList();
    public LargeInteger(String value) throws IllegalArgumentException {
    //Declare variables
    boolean neg = false;
    int num = 0;
    int start = 0;
    char ch = ' ';
    Integer tempObj = new Integer(num);
    //If the first character is not a - sign or it is less than the character 0
    //or it is greater than the character zero, then throw
    //IllegalArgumentException
    //else add digits into linked list as integers
    if(value.startsWith("-")) {
    neg = true;
    start = 1;
    } else if ( !Character.isDigit(value.charAt(0)) ) {
    throw new IllegalArgumentException();
    for (int j = value.length()-1; j >= start; j--) {
    ch = value.charAt(j);
    if (Character.isDigit(ch)) {
    num = Character.getNumericValue(ch);
    tempObj = new Integer(num);
    digits.add(tempObj);
    } else {
    throw new IllegalArgumentException();
    } // end Constructor
    public static void main(String[] args) {
    LargeInteger a = new LargeInteger("954");
    LargeInteger b = new LargeInteger("123456789");
    LargeInteger c = a.plus(b);
    System.out.println( c.toString() );
    System.out.println( a.toString() );
    System.out.println( b.toString() );
    /** Calculates the sum of this LargeInteger object with the one passed
    * as a parameter.
    * @param other The number to add to the current value.
    * @return The sum of this LargeInteger and the value passed as a
    * parameter.
    public LargeInteger plus(LargeInteger other) {
         int i = 0;
    LargeInteger result = new LargeInteger("0");
    int carry = 0;
    ListIterator onfiltered = digits.listIterator();
    ListIterator two = other.digits.listIterator();
    //Add digits in linked list
    for (; i < digits.size() && i < other.digits.size(); i++) {
    result.digits.addFirst(
    new Integer(
    (((Integer) digits.get(i)).intValue()
    + ((Integer) other.digits.get(i)).intValue()
    + carry)
    % 10));
    carry =
    (((Integer) digits.get(i)).intValue()
    + ((Integer) other.digits.get(i)).intValue()
    + carry)
    / 10;
    onfiltered.next();
    two.next();
    //Append any remaining digits from this value to the result's
    //left
    for(; i < digits.size();i++){
         result.digits.addFirst(new Integer((((Integer)digits.get(i)).intValue() + carry) % 10));
         carry = (((Integer)digits.get(i)).intValue() + carry) / 10;
         onfiltered.next();
    //Append any remaining digits from the other value to the result's
    //left
    for(; i < digits.size();i++){
         result.digits.addFirst(new Integer((((Integer)other.digits.get(i)).intValue() + carry) % 10));
         carry = (((Integer)other.digits.get(i)).intValue() + carry) / 10;
         two.next();
    if(carry != 0){
         result.digits.addFirst(new Integer(carry));
    return result;
    } // end plus

    Use a debugger.
    Or put in some debugging statements.

  • 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 Lists

    I am trying to create a linked list with an object called ClassID But I am confused on the constructor. Could someone point me in teh right direction. this is what i got:
    import java.io.*
    public class Link
         public ClassID id;
         public Link next;
    public Link(ClassID id)
         id = new ClassID(id);
         

    Sorry, after rereading your initial post a third time, I see there is more to what you are asking and displaying than is easily discernable.
    I am assuming you mant the linked list wis of type ClassId, if ClassId was actually meant to be the data objects stored in the list then you must give your Linked List a new name, so say ClassLl. If this is the case replace ClassId with ClassLl in my example below.
    First, when you are using a constructor you don't really want to pass in "id"s and you definitely don't need "next". This is because the purpose of the constructor is to build a new linked list, and id and next should never be used in making a new linked list. The ClassId object if you have to create your own linked list without using the collections libraries should have a id and next field, but they should not be necessary for the constructor. The id, next, and ClassId if it is meant to be the data stored all should only come into play in methods manipulating the linked list.
    At most, you may have an already cronstructed linked list that you plan to pass to the linked list, but there is never a reason to pass id or next to a constructor.
    so
    public class List
         public ClassID id = new ClassId(); //or = new LinkedList() if allowed
            public List()  //there is no preexisting linkedlist being passed in
         public List(ClassID inID)  //inId is a linkedlist
              id = inID;
    }In short, worry about setting up your linked list before you start trying to fill it with stuff.

  • How is Define Links on Confirmation Page-link list key linked to iviews?

    Hi All,
    Although there is no ESS in MSS as such in our new portal (hompage framework), we have configured it as much as we could, so that it was similar to the previous ESS in MSS.  We have used a copy of the ESS address iview for the ESS in MSS emergency contact.
    The trouble is that the links on the confirmation page are trying to resolve to ESS rather than resloving to an option in MSS.  E.G. the Go to Address Overview link is trying to resolve to the address overview screen in ESS rather than MSS.
    I have  checked the parameters on the view and there does't appear to be anywhere that you can assign the lnk list key.  Similarly I have checked the resources and the services parameters and have nowhere to put this key.
    So my question is, how exactly is the link list key attached to an iview? In our case the iviews are in 2 different PCD's so how can I create a zlink list key and assign it to the copied address iview?
    Many thanks,
    Liz.

    The confirmation links are defined in V_T7XSSSERLNK - as far as I can see they are linked to services not iviews
    defined in HpF
    Also "ESS in MSS" is available as "Self-Service for My Employee" in MSS Related Activities for certain SAP releases
    Best wishes
    Stuart

  • Selection Sort using Linked Lists

    As the subject says, I'm trying to implement a selection sort method on a linked list structure. I've already created a bubble sort, but I can't seem to get this method to work correctly. The Node and LinkedList classes were written by me, and I know they work correctly (because of the other methods work right).
    public void selectionSort(LinkedList list) {
            int iterationsINNER = 1, iterationsOUTER = 1, swaps = 0, comparisons = 1;
            if(list.isEmpty())
                System.out.println("List is currently empty.");
            else if (list.size() == 1)
                System.out.println("List is already sorted.");
            else {
                Node pointer = list.getFirst();
                Node current;
                boolean exchangeMade;
                while (pointer.getNext().getNext() != null) {
                    current = pointer;
                    exchangeMade = false;
                    iterationsOUTER++;
                    while (current.getNext() != null && !exchangeMade) {
                        if(current.getNext().getData() < pointer.getData()) {
                            int temp = pointer.getData();
                            pointer.setData(current.getNext().getData());
                            current.getNext().setData(temp);
                            exchangeMade = true;
                            iterationsINNER++;
                            swaps++;
                            comparisons++;
                        current = current.getNext();
                    pointer = pointer.getNext();
              //  System.out.println("Comparisons: " + comparisons + " \nSwaps: " + swaps + " \nIterations: " + iterationsINNER+iterationsOUTER);
        }For instance, if I run this bit of code...
    LinkedList list = new LinkedList();
            list.insert(5);
            list.insert(29);
            list.insert(2);
            list.insert(1);
            list.insert(13);
            list.insert(8);
            list.insert(30);
            list.insert(3);
            sort.selectionSort(list);
            list.print();The output is...
    1
    8
    13
    3
    2
    29
    30
    5
    Anyone have any idea what is going wrong, or is anymore information needed?
    PS: I also need to create a insertion sort method with this, and I've been told I need to reverse the list for the insertion sort to work correctly. Any tips on how to implement this method too? :)

    I've changed it up a bit, and it works, but is this still a bubble sort? I've tried uncommenting that section that keeps track of the iterations and such, but I know they can't be right. Does this look correct? I basically just removed that boolean check...
    public void selectionSort(LinkedList list) {
            int iterationsINNER = 1, iterationsOUTER = 1, swaps = 0, comparisons = 1;
            if(list.isEmpty())
                System.out.println("List is currently empty.");
            else if (list.size() == 1)
                System.out.println("List is already sorted.");
            else {
                Node pointer = list.getFirst();
                Node current;
                while (pointer.getNext() != null) {
                    current = pointer;
                    iterationsOUTER++;
                    while (current.getNext() != null) {
                        comparisons++;
                        if(current.getNext().getData() < pointer.getData()) {
                            int temp = pointer.getData();
                            pointer.setData(current.getNext().getData());
                            current.getNext().setData(temp);
                            iterationsINNER++;
                            swaps++;
                        current = current.getNext();
                    pointer = pointer.getNext();
                System.out.println("Comparisons: " + comparisons + " \nSwaps: " + swaps + " \nIterations: " + iterationsINNER+iterationsOUTER);
        }And no, I tried and I don't get a NullPointerException if I have a list of 2.
    Edited by: birdboy30 on Dec 3, 2007 7:23 PM

  • A linked list question.

    So, I believe I understand linked lists for the most part, except for two lines....
        boolean add(Transaction item)
            for (Transaction curr = first; curr != null; curr = curr.next)
                if (curr.part_num == item.part_num)
                    return false;
            Transaction newItem = new Transaction();
            newItem.transcode = item.transcode;
            newItem.description = item.description;
            newItem.part_num = item.part_num;
            newItem.quantity = item.quantity;
            newItem.next = first;
            first.next = newItem;
            return true;
        }first is null, so First.next would be the first available space for actual insertion, and this is why it then puts null as newItem.next (the end of the list), and sticks newItem in first.next?
    Im glad I read that pass by value thing earlier at the Java Ranch place...
    Heres my actual question: When newItem.next = first; is called, it just copies null as the next field, but leaves the null in first alone right? And then it takes first.next and makes newItem copy into that field, thus inserting the first real item in the list?
    Please tell me I made that connection right. :-D
    Thanks!!

    Pictures are worth a hundred words with linked lists. Did you even put a pencil and paper next to your computer while doing this program, so that you could draw what is happening when you get confused?
    If first is null, then the for loop is skipped--because first is assigned to curr and the loop only executes when curr is not equal to null.
    So, this happens:
    newItem = new Transaction()
    int Transcode = 0
    String description = null
    int partNumber = 0
    int quantity = 0
    Tranasaction next = nullThen values are assigned to each field:
    newItem
    int Transcode = 10
    String description = "screw"
    int partNumber = 46
    int quantity = 200
    //freeze execution here:
    Tranasaction next = null (what will happen here??)Your assumption was:
    Transaction first = null
    That means first does not refer to a Transaction object. Therefore, first does not have a description member, a quantity member, etc., and this is what things look like just before newItem.next = first; is executed:
    newItem ----> Transaction
                  int Transcode = 10
                  String description = "screw"
                  int partNumber = 46
                  int quantity = 200
                  Tranasaction next = null
    first ------> nullNow,
    When newItem.next = first; is calledthings change to this:
    newItem ----> Transaction
                  int Transcode = 10
                  String description = "screw"
                  int partNumber = 46
                  int quantity = 200
          /-------Tranasaction next
    first ------> null That isn't what you want. When you add() a Transaction object to the end of your linked list, it's next member should be null. It's the end of the chain, so there is no next.
    And then it takes first.next and makes newItem copy
    into that field, thus inserting the first real item in the
    list?No. first is null so it does not refer to a Transaction object, and therefore there is no next member variable and consequently no such thing as first.next. You need to understand that null and a Transaction object that has 0 for every member are not the same.
    But suppose for a minute that null and a Transaction object with zeros for every field were the same thing, so that first.next existed. If that was the case, then you could assign newItem to first.next. But, then you would be left with this:
    first
    int Transcode = 0
    String description = null
    int partNumber = 0
    int quantity = 0
    Tranasaction next = newItemWould you want the first Transaction object in your LinkedList to be almost entirely empty?
    Instead, if first is null, you want to make first refer to newItem, i.e. you want to do this:
    newItem ----> Transaction
                  int Transcode = 10
                  String description = "screw"
                  int partNumber = 46
                  int quantity = 200
                  Tranasaction next = null
    first ----/   nullThen when the add() method ends, since newItem is a local variable, it will be destroyed leaving you with this:
                  Transaction
                  int Transcode = 10
                  String description = "screw"
                  int partNumber = 46
                  int quantity = 200
                  Tranasaction next = null
    first ----/   null

  • Question about Linked Lists

    I'm doing an assignment on linked lists and I'm having trouble understanding the insert method. I'm using the one from the book and it works fine, but I don't quite understand it.
    public void insert(Object o) {
    Node n = new Node(o,current);
    if (previous == null)
    head = n;
    else
    previous.next = n;
    current = n;
    It's my understanding that current is the value that your currently at in the list. Previous is equal to the value before the current. So, previous.next is equal to current. This reasoning won't make the list progress with this code. Can someone tell me what I'm not understanding, or explain how this progresses?

    Thanks, that helps alot. Now, I have another question. I need to add and remove nodes from the list. I have it setup where the user can choose what node to delete. It compiles and runs fine, but when I try to delete a node, it doesn't delete it. Doing some troubleshooting, I found that it gets into the for loop, but doesn't do anything with the if/else statement. I put a printline in the if and else part, and it never printed out the statement in the if statement or in the else statement. Here's the code I'm using. getLentgh() is a method I wrote to return an integer value of how many nodes are in the list. I've also tried putting in a printline after the for loop, but still in the try, it didn't print it out.
    else if(source == remove) {
    String del = JOptionPane.showInputDialog("Enter an integer to remove.");
    Node temp = new Node(del,current);
    if(del != null){
    try{
         for(int c = 0; c < list.getLength(); c++){            
         if(temp.data == current.data){
              list.remove();
              c = list.getLength();
         else{
              list.advance();     
    }catch(NullPointerException e){
    }

  • 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

  • How to add different data types in Linked list?

    The basic idea is that I want to implement a linked list like the one which we generally implement in C. I need to store different data types in a single node. Is it possible to implement like this or I have to implement a linked list for each different data type?

    I have an application program in which there is a form. In this form there are different text fields in which data is to be inserted by the user. These data's will be inserted into the database. I want to hit the database only once. So I need to store these data in a data structure before I insert into the database. I think it will be easy for me to handle the data in a linked list if I can have different data types in a single node.
    Moreover, I think u're not getting my question. This pic will help u.
    http://img522.imageshack.us/img522/4500/sampler.jpg
    I'm not sure about that the code which u have written will have different data types in single node. I have to try that.
    And of course if anyone has any better idea than me, it will be very helpful.

  • Quick Question about linked lists

    If I have a linked list can i save it to a file directly with the Serializable interface or would I have to iterate through each element and write each element to the file?

    yeah, it seems as though I can
    However, I am having a problem reading it back. I guess I don't know how to initialize the values in the list, as it doens't recognize anything until I add an item to it and it adds this item to the front, then any other items after that it will add to the back, when i want this first addition to be in the back as well.
    when I initialize the class i call
    list.add(loadList());
    loadList()
    public MyList loadList() {
               try {
                 FileInputStream fis = new FileInputStream("data.dat");
                 ObjectInputStream in = new ObjectInputStream(fis);
                 list = (MyList)in.readObject();
                 in.close();
                 return list;
               catch (Exception e) {
                   System.out.println(e);
              return list;
           }list.add()
    public void add(int index, Object o)
              if (index == 0) addFirst(o);
              else if (index >= size) addLast(o);
              else {
                   Node current = first;
                   for (int i = 1; i < index; i++)
                        current.prev = current;
                        current = current.next;
                   Node temp = current.next;
                   current.next = new Node(o);
                   current.prev = current;
                   (current.next).next = temp;
                   size++;
         }any ideas?

Maybe you are looking for