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.

Similar Messages

  • Need help regarding Linked List

    I'm a beginner who just spent ages working on the following code.. but need help on re-implementing the following using a linked list, i.e. no array is allowed for customer records but you still can use arrays for names, address, etc.. Hopefully I've inserted enough comments..
    Help very much appreciated!! Thanks! =]
    import java.util.Scanner;
    import java.io.*;
    public class Bank
    /* Private variables declared so that the data is only accessible to its own
         class, but not to any other class, thus preventing other classes from
         referring to the data directly */
    private static Customer[] customerList = new Customer[30];               
         //Array of 30 objects created for storing information of each customer
    private static int noOfCustomers;                                                       
         //Integer used to store number of customers in customerList
         public static void main(String[] args)
              Scanner sc = new Scanner(System.in);
              menu();
         public static void menu()
              char choice;
              String filename;
              int custId,counter=0;
              double interestRate;
    Scanner sc = new Scanner(System.in);
              do
              //Displaying of Program Menu for user to choose
         System.out.println("ABC Bank Customer Management System Menu");     
         System.out.println("========================================");
         System.out.println("(1) Input Data from File");
         System.out.println("(2) Display Data");
         System.out.println("(3) Output Data to File");
                   System.out.println("(4) Delete Record");
                   System.out.println("(5) Update Record");
         System.out.println("(Q) Quit");
                   System.out.println();
                   System.out.print("Enter your choice: ");
                   String input = sc.next();
                   System.out.println();
                   choice = input.charAt(0);     
              //switch statement used to assign each 'selection' to its 'operation'               
         switch(choice)
         case '1': int noOfRecords;
                                       System.out.print("Enter file name: ");
              sc.nextLine();                                             
              filename = sc.nextLine();
                                       System.out.println();
              noOfRecords = readFile(filename);
    System.out.println(+noOfRecords+" records read.");
              break;
         case '2': displayRecords();
              break;
         case '3': writeFile();
         break;
                        case '4': System.out.print("Enter account ID to be deleted: ");
                                       sc.nextLine();
                                       custId = sc.nextInt();
                                       deleteRecord(custId);
                                       break;
                        case '5': if(counter==0)
              System.out.print("Enter current interest rate for saving account: ");
                                            sc.nextLine();
                                            interestRate = sc.nextDouble();
                                            update(interestRate);
                                            counter++;
                                       else
              System.out.println("Error: Accounts have been updated for the month.");
                                            break;
                   }System.out.println();
         }while(choice!='Q' && choice!='q');
    /* The method readFile() loads the customer list of a Bank from a specified
         text file fileName into customerList to be stored as array of Customer
         objects in customerList in ascending alphabetical order according to the
         customer names */
    public static int readFile(String fileName)
         int custId,i=0;
              String custName,custAddress,custBirthdate,custPhone,custAccType;
              double custBalance,curRate;
              boolean d;
    /* Try block to enclose statements that might throw an exception, followed by
         the catch block to handle the exception */
    try
                   Scanner sc = new Scanner(new File(fileName));
    while(sc.hasNext())          
    /* sc.next() gets rid of "Account", "Id" and "=" */
    sc.next();sc.next();sc.next();
    custId = sc.nextInt();
                        d=checkDuplicate(custId);               
    /* checkDuplicate() is a method created to locate duplicating ids in array */
    if(d==true)
    /* A return value of true indicates duplicating record and the sc.nextLine()
         will get rid of all the following lines to read the next customer's record */
                             sc.nextLine();sc.nextLine();sc.nextLine();
                             sc.nextLine();sc.nextLine();sc.nextLine();
                             continue;     
    /* A return value of false indicates no duplicating record and the following
         lines containing the information of that customer's record is being read
         in */
                        if(d==false)
    /* sc.next() gets rid of "Name" and "=" and name is changed to upper case*/
         sc.next();sc.next();
         custName = sc.nextLine().toUpperCase();
    /* sc.nextLine get rids of the following lines to read the next customer's
         record if length of name is more than 20 characters*/
         if(custName.length()>21)
    System.out.println("Name of custId "+custId+" is more than 20 characters");
                                  System.out.println();
         sc.nextLine();sc.nextLine();sc.nextLine();sc.nextLine();
         continue;
    /* sc.next() gets rid of "Address" and "=" */           
         sc.next();sc.next();
         custAddress = sc.nextLine();
    /* sc.nextLine get rids of the following lines to read the next customer's
         record if length of address is more than 80 characters*/                         
                             if(custAddress.length()>81)
    System.out.println("Address of custId "+custId+" is more than 80 characters");
                                  System.out.println();
         sc.nextLine();sc.nextLine();sc.nextLine();sc.nextLine();
         continue;
    /* sc.next() gets rid of "DOB" and "=" */                              
         sc.next();sc.next();
         custBirthdate = sc.nextLine();
    /* sc.nextLine get rids of the following lines to read the next customer's
         record if length of date of birth is more than 10 characters*/                         
                             if(custBirthdate.length()>11)
    System.out.println("D.O.B of custId "+custId+" is more than 10 characters");
                                  System.out.println();
         sc.nextLine();sc.nextLine();sc.nextLine();sc.nextLine();
         continue;
    /* sc.next() gets rid of "Phone", "Number" and "=" */                              
         sc.next();sc.next();sc.next();
         custPhone = sc.nextLine();
    /* sc.nextLine get rids of the following lines to read the next customer's
         record if length of phone number is more than 8 characters*/                         
                             if(custPhone.length()>9)
    System.out.println("Phone no. of custId "+custId+" is more than 8 characters");
                                  System.out.println();
         sc.nextLine();sc.nextLine();sc.nextLine();sc.nextLine();
         continue;
    /* sc.next() gets rid of "Account", "Balance" and "=" */                              
         sc.next();sc.next();sc.next();
         custBalance = sc.nextDouble();
    /* sc.next() gets rid of "Account", "Type" and "=" */                              
                             sc.next();sc.next();sc.next();
                             custAccType = sc.next();
                             if(custAccType.equals("Saving"))
    customerList[noOfCustomers] = new Account1(custId,custName,custAddress,custBirthdate,custPhone,custBalance,custAccType);
    sc.nextLine();
                                                 noOfCustomers++;
                                                 i++;
    else if(custAccType.equals("Checking"))
    customerList[noOfCustomers] = new Account2(custId,custName,custAddress,custBirthdate,custPhone,custBalance,custAccType);
                                                 sc.nextLine();
                                                 noOfCustomers++;
                                                 i++;
    else if(custAccType.equals("Fixed"))
    sc.next();sc.next();sc.next();sc.next();
                                                 curRate = sc.nextDouble();
                                                 Account3 temp = new Account3(custId,custName,custAddress,custBirthdate,custPhone,custBalance,custAccType,curRate);
                                                 customerList[noOfCustomers]=temp;
                                                 sc.nextLine();
                                                 noOfCustomers++;
                                                 i++;
                             else
                                  System.out.println("Account type not defined.");
         if(noOfCustomers==30)
         System.out.println("The customer list has reached its maximum limit of 30 records!");
         System.out.println();
         return noOfCustomers;
    //Exceptions to be caught
    catch (FileNotFoundException e)
    System.out.println("Error opening file");
    System.exit(0);
    catch (IOException e)
    System.out.println("IO error!");
    System.exit(0);
    /* Bubblesort method used to sort the array in ascending alphabetical order
         according to customer's name */
    bubbleSort(customerList);
              return i;
    /* The method displayRecords() displays the data of the customer records on
         screen */
    public static void displayRecords()
    int k;
    /* Displaying text using the printf() method */
         for(k=0;k<noOfCustomers;k++)
         System.out.printf("Name = %s\n", customerList[k].getName());
         System.out.printf("Account Balance = %.2f\n", customerList[k].getBalance());
         System.out.printf("Account Id = %d\n", customerList[k].getId());
    System.out.printf("Address = %s\n", customerList[k].getAddress());
    System.out.printf("DOB = %s\n", customerList[k].getBirthdate());
    System.out.printf("Phone Number = %s\n", customerList[k].getPhone());
         String type = customerList[k].getAccType();
         System.out.println("Account Type = " +type);
    if(type.equals("Fixed"))
         System.out.println("Fixed daily interest = "+((Account3)customerList[k]).getFixed());
         System.out.println();               
    /* The method writeFile() saves the content from customerList into a
         specified text file. Data is printed on the screen at the same time */
    public static void writeFile()
    /* Try block to enclose statements that might throw an exception, followed by
    the catch block to handle the exception */
    try
    int i;
              int n=0;
    //PrintWriter class used to write contents of studentList to specified file
              FileWriter fwStream = new FileWriter("newCustomers.txt");
              BufferedWriter bwStream = new BufferedWriter(fwStream);
              PrintWriter pwStream = new PrintWriter(bwStream);     
    for(i=0;i<noOfCustomers;i++)
         pwStream.println("Account Id = "+customerList.getId());
              pwStream.println("Name = "+customerList[i].getName());
    pwStream.println("Address = "+customerList[i].getAddress());
    pwStream.println("DOB = "+customerList[i].getBirthdate());
    pwStream.println("Phone Number = "+customerList[i].getPhone());
              pwStream.printf("Account Balance = %.2f\n", customerList[i].getBalance());
              pwStream.println("Account Type = "+customerList[i].getAccType());
                   if(customerList[i].getAccType().equals("Fixed"))
                        pwStream.println("Fixed Daily Interest = "+((Account3)customerList[i]).getFixed());
              pwStream.println();
              n++;
    //Closure of stream
    pwStream.close();
              System.out.println(+n+" records written.");
    catch(IOException e)
    System.out.println("IO error!");     
    System.exit(0);
         //Deletes specified record from list
    public static void deleteRecord(int id)
    int i;
              i=locate(id);
    if(i==200)
    //checking if account to be deleted does not exist
    System.out.println("Error: no account with the id of "+id+" found!");
              //if account exists
    else
                        while(i<noOfCustomers)
                             customerList[i] = customerList[i+1];
                             i++;
                        System.out.println("Account Id: "+id+" has been deleted");
                        --noOfCustomers;
         //Updates the accounts
    public static void update(double interest)
    int i,j,k;
              double custBalance,addition=0;
    for(i=0;i<noOfCustomers;i++)
                        if(customerList[i] instanceof Account1)
                             for(j=0;j<30;j++)
                                  addition=customerList[i].getBalance()*interest;
                                  custBalance=customerList[i].getBalance()+addition;
                                  customerList[i].setBalance(custBalance);
                        else if(customerList[i] instanceof Account2)
                             continue;
                        else if(customerList[i] instanceof Account3)
                             for(j=0;j<30;j++)
    addition=customerList[i].getBalance()*((Account3)customerList[i]).getFixed();
    custBalance=customerList[i].getBalance()+addition;
    customerList[i].setBalance(custBalance);
                        else
                             System.out.println("Account type not defined");
              System.out.println("The updated balances are: \n");
              for(k=0;k<noOfCustomers;k++)
    System.out.printf("Name = %s\n", customerList[k].getName());
    System.out.printf("Account Balance = %.2f\n", customerList[k].getBalance());
    System.out.println();
    /* ================== Additional methods ==================== */     
    /* Bubblesort method to sort the customerList in ascending alphabetical
         order according to customer's name */
    public static void bubbleSort(Customer[] x)
    int pass, index;
    Customer tempValue;      
    for(pass=0; pass<noOfCustomers-1; pass++)          
    for(index=0; index<noOfCustomers-1; index++)
    if(customerList[index].getName().compareToIgnoreCase(customerList[index+1].getName()) > 0)
    tempValue = x[index];
    x[index] = x[index+1];
    x[index+1]= tempValue;
    /* Method used to check for duplicated ids in array */     
         public static boolean checkDuplicate(int id)
              int i;
              for(i=0;i<noOfCustomers;i++)
                   if(id == customerList[i].getId())
    System.out.println("Account Id = "+id+" already exists");
                        System.out.println();
    return true;
              }return false;
    /* Method to seach for account id in array */
         public static int locate(int id)
              int j;
              for(j=0;j<noOfCustomers;j++)
                   if(customerList[j].getId()==id)
                        return j;
              j=200;
              return j;
    import java.util.Scanner;
    public class Customer
    /* The following private variables are declared so that the data is only
         accessible to its own class,but not to any other class, thus preventing
         other classes from referring to the data directly */
         protected int id;               
         protected String name,address,birthdate,phone,accType;                              
         protected double balance;               
    // Null constructor of Customer
         public Customer()
              id = 0;
              name = null;
              address = null;
              birthdate = null;
              phone = null;
              balance = 0;
              accType = null;
    /* The following statements with the keyword this activates the Customer
         (int id, String name String address, String birthdate, String phone, double
         balance) constructor that has six parameters of account id, name, address,
         date of birth, phone number, account balance and assign the values of the
         parameters to the instance variables of the object */     
         public Customer(int id, String name, String address, String birthdate, String phone, double balance, String accType)
    //this is the object reference that stores the receiver object     
              this.id = id;
              this.name = name;                         
              this.address = address;
              this.birthdate = birthdate;
              this.phone = phone;
              this.balance = balance;
              this.accType = accType;
    /* The following get methods getId(), getName(), getAddress(), getBirthdate(),
         getPhone(), getBalance() return the values of the corresponding instance
         properties */     
         public int getId()
              return id;
         public String getName()
              return name;
         public String getAddress()
              return address;
         public String getBirthdate()
              return birthdate;
         public String getPhone()
              return phone;
         public double getBalance()
              return balance;
         public String getAccType()
              return accType;
    /* The following set methods setId(), setName(), setAddress(), setBirthdate(),
         setPhone and setBalance() set the values of the corresponding instance
         properties */
         public void setId (int custId)
              id = custId;
         public void setName(String custName)
              name = custName;
         public void setAddress (String custAddress)
              address = custAddress;
         public void setBirthdate (String custBirthdate)
              birthdate = custBirthdate;
         public void setPhone (String custPhone)
              phone = custPhone;
         public void setBalance (double custBalance)
              balance = custBalance;
         public void setAccType (String custAccType)
              accType = custAccType;
    class Account1 extends Customer
         public Account1(int id, String name, String address, String birthdate, String phone, double balance, String accType)
              super(id,name,address,birthdate,phone,balance,accType);
              this.id = id;
              this.name = name;                         
              this.address = address;
              this.birthdate = birthdate;
              this.phone = phone;
              this.balance = balance;
              this.accType = accType;
    class Account2 extends Customer
         public Account2(int id, String name, String address, String birthdate, String phone, double balance, String accType)
              super(id,name,address,birthdate,phone,balance,accType);
              this.id = id;
              this.name = name;                         
              this.address = address;
              this.birthdate = birthdate;
              this.phone = phone;
              this.balance = balance;
              this.accType = accType;
    class Account3 extends Customer
         protected double fixed=0;
         public Account3(int id, String name, String address, String birthdate, String phone, double balance, String accType, double fixed)
              super(id,name,address,birthdate,phone,balance,accType);
              this.id = id;
              this.name = name;                         
              this.address = address;
              this.birthdate = birthdate;
              this.phone = phone;
              this.balance = balance;
              this.accType = accType;
              this.fixed = fixed;
         public double getFixed()
              return fixed;
    Example of a customers.txt
    Account Id = 123
    Name = Matt Damon
    Address = 465 Ripley Boulevard, Oscar Mansion, Singapore 7666322
    DOB = 10-10-1970
    Phone Number = 790-3233
    Account Balance = 405600.00
    Account Type = Fixed
    Fixed Daily Interest = 0.05
    Account Id = 126
    Name = Ben Affleck
    Address = 200 Hunting Street, Singapore 784563
    DOB = 25-10-1968
    Phone Number = 432-4579
    Account Balance = 530045.00
    Account Type = Saving
    Account Id = 65
    Name = Salma Hayek
    Address = 45 Mexican Boulevard, Hotel California, Singapore 467822
    DOB = 06-04-73
    Phone Number = 790-0000
    Account Balance = 2345.00
    Account Type = Checking
    Account Id = 78
    Name = Phua Chu Kang
    Address = 50 PCK Avenue, Singapore 639798
    DOB = 11-08-64
    Phone Number = 345-6780
    Account Balance = 0.00
    Account Type = Checking
    Account Id = 234
    Name = Zoe Tay
    Address = 100 Blue Eyed St, Singapore 456872
    DOB = 15-02-68
    Phone Number = 456-1234
    Account Balance = 600.00
    Account Type = Saving

    1) When you post code, please use[code] and [/code] tags as described in Formatting tips on the message entry page. It makes it much easier to read.
    2) Don't just post a huge pile of code and ask, "How do I make this work?" Ask a specific question, and post just enough code to demonstrate the problem you're having.
    3) Don't just write a huge pile of code and then test it. Write a tiny piece, test it. Then write the piece that will work with or use the first piece. Test that by itself--without the first piece. Then put the two together and test that. Only move on to the next step after the current step produces the correct results. Continue this process until you have a complete, working program.

  • Circular Linked List Help

    Hi,
    I'm developing a circular linked list class.. However everytime I add to the front of the list it overwrites the first element in the list.. I pretty confused at the moment. If anyone could assist me in what I'm doing wrong it would be greatly appreciated..
    My Class:
    public class CNode<T>
         public T nodeValue;          //data held by the node
         public CNode<T> next;     //next node in the list
         //default constructor; next references node itself
         public CNode()
              nodeValue = null;
              next = this;
         //constructor; initializes nodeValue to item
         //and sets the next to reference the node itself
         public CNode(T item)
              nodeValue = item;
              next = this;
    }My addFirst:
    public static <T> void addFirst(CNode<T> header, T item)
              CNode<T> curr;
              CNode<T> newNode = new CNode<T>(item);
              //header.next = newNode;
              //newNode.next = header;
              curr = header;
              newNode.next = header;
              curr.next = newNode;
         }

    You need a Node class and a class that manages the nodes. The class the manages the nodes is typically called something like MyLinkedList. The MyLinkedList class will typically have a member called 'head' or 'first' and another member called 'last', 'end', or 'tail'. Those members will contain references to the first node and the last node respectively.
    The methods like add(), remove(), find(), etc. will be members of the MyLinkedList class--not the Node class. The add() method of the MyLinkedList class will create a node, set the value of the node, and then set the next member to refer to the proper node or null if the node is added to the end of the list. Therefore, there is really no need for a default constructor in the node class. The MyLinkedList class will always set the value of the node, and then set it's next member to refer to something.
    You might want to try to write a linear linked list first, and get that working, and then modify it to make it a circular linked list. In addition, you should be drawing pictures of nodes with arrows connecting the different nodes to understand what's going on. Whenver the next member of a node refers to another node, draw an arrow starting at the next member and ending at the node it refers to. The pictures will be especially helpful when you write functions like add().
    Message was edited by:
    7stud

  • C/C++ Alphabetical Linked List

    For my programming class, we have to create a linked list, which is arranged in order of when you added them. This was Assignment Six. Assignment 8 is to add an alphabetical list to this program, alongside the list in order.
    My professor wants us to have a "donor struct" and an "alpha struct" that points to the donor, as well as the next in the list.
    He isn't helping me figure this out so I figured I'd ask for help here.
    My 'modifyDonor()' function is broken, it deletes everything after whatever record you are trying to modify. There is also a problem in my 'prepareFiles()' function. Whatever the last entry is, is copied in twice.
    I would rather have this alphabetical stuff figured out before I work on those things.
    I'm not really allowed to use C++ stuff (classes, objects, etc.), because we haven't learned them yet, but if you can do it, and figure it out, then explain it to me. I'll take it.
    (Also, if you could post the edits to my source code, that would rad!)
    Below is a link to my source code and data file.
    http://www.dcpwrpodcast.com/DCPWR/Help.Sponsorhipfiles/Archive.zip
    Any help you can provide is greatly appreciated!

    Unfortunately, I can't really pinpoint an exact place where you are doing something wrong. I don't think you really understand the linked list concepts yet. The first thing I changed was getting rid of where you increment "first" in modifyDonation. Resetting "first" effectively destroys your list. You have additional problems with the other pointers.
    So, first of all, you have too many global pointers. You need one global pointer, named "head". Any time you iterate through the list (to print, find, etc.) you create a temp donor pointer, assign "head" to it and increment that temp pointer. The last node in your list should have NULL as its "next" pointer.
    To add a node, create a new node with NULL as its next pointer. Find where you want to insert, make the new node's next pointer point to the next pointer of the node at the insertion point. Then make the next pointer of the node at the insertion point point to the new node.
    To delete a node, find the node to delete. Make the previous node's next pointer point to the dead node's next pointer. Then delete the node.
    You don't change any pointers (other than temp ones) during a modify or print.
    At this point, all you have left is the special case of the first node. The last node isn't special because you can do the same copying of the next pointer as normal, even though that pointer is NULL.
    The first node, however, needs careful handling. If you delete the first node, you have to reset your head pointer. If you insert a new first node, you have to reset your head pointer. Sometimes it is easier to have your head node be a special, empty node. Then, you don't have to re-assign head. Also, when searching through the list, your "current" pointer should be the "previous" node. That way, when you are ready to insert, your "current" pointer is the "previous" node and the insertion is easy. The code looks a bit ugly because you'll have things like "if(current->next && current->next->id == id)". But you'll also need an extra, redundant null check.
    Hopefully this makes some sense. Your code is more complicated than it needs to be. You have too many globals. You are modifying those globals far too frequently. You want lots of:
    void modifyDonation(donor * node);
    donor * current = head->next;
    while(current)
    if(current->id == id)
    modifyDonation(current);
    break;
    current = current->next;
    insert and delete are more difficult
    void insertDonation(donor * previous, donor * next);
    donor * current = head;
    while(current)
    if(!current->next || (current->next->id == id))
    insertDonation(current, current->next);
    break;
    current = current->next;
    To maintain a natural order and a sorted order, you'll need two head pointers. After you add or insert into the natural list, you insert into the sorted list according to the sort criteria. Delete is the same for both lists.

  • Linked lists revisited

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

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

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

  • Linked Lists, Hashing, and sore heads.

    I am working with a team on a java program as part of an algorithms assignment. We have completed the program however I'm convinced its not working. The program is supposed to carry out a defined number of searches, additionions and deletions to a linked list and time it. We have been supplied with a number of ext files with random numbers for testing purposes.
    The text files are different sizes. We are finding that our results are the same regardless which file we use and which arguments are passed into the program. I would be greatful if someone could cast their eye over the work and let us know what you think.
    All files are at
    http://students.odl.qmul.ac.uk/~dm07/algorithms/.
    IntSet.java is the program we have completed from a skeleton code.
    Evaluator.java is the wrapper provided. data.zip is a full file of the
    different test text files although there are two on here for quick download.
    Any direction or feedback would be really appreciated.
    Dermot.

    Here is the result for the 50 random numbers text file :
    D:\Coursework\Algorithms>java Evaluator size-50-random.txt 10000
    Setting up, please wait ...
    Finished setting up.
    Start searches
    It took 0.010 seconds for 10000 searches
    It took 0.020 seconds for 10000 additions
    It took 0.010 seconds for 10000 deletions
    And here is the result for hte 50000 random numbers text file :
    D:\Coursework\Algorithms>java Evaluator size-50000-random.txt 10000
    Setting up, please wait ...
    Finished setting up.
    Start searches
    It took 0.010 seconds for 10000 searches
    It took 0.020 seconds for 10000 additions
    It took 0.000 seconds for 10000 deletions
    As you can see they are virtually identical. Even after running a number of times and working out averages they are the same. I thought that the results should be exponential but they are not. I understand that results should change from pc setup to pc setup, depending on processor etc but we are not getting this.
    Dermot.

  • Is my code a Linked Lists or not?

    Hello everyone,
    [I hope I am in the right forum]
    I am trying to learn how to implement Linked Lists with Java. I have written a small code and I would appreceate it a lot if any one would be kind enough to check if this code is really a linked list.
    I tried to make a list with 3 nodes, with no helping methods for adding and removing nodes. Just a simple example. This is my code:
    public class myList{
         public static final long serialVersionUID = 24362462L;
         //node pointer important to define private, so not share same value
         private myList pointer;
         //node data
         private String nodeData;
    public static void main(String args[]){
    //Give memory to nodes
    myList Node1 = new myList();
    myList Node2 = new myList();
    myList Node3 = new myList();
    //Make Node1
    Node1.pointer = Node2;//give value to pointer
    Node1.nodeData = "Hi i am data contained in Node 1.";
    //Make Node2
    Node2.pointer = Node3;
    Node2.nodeData = "Hi i am data contained in Node 2.";
    //Make Node3
    Node3.pointer = null;
    Node3.nodeData = "Hi i am data contained in Node 3.";
    //Display Data
    System.out.println(Node1.nodeData);
    System.out.println(Node2.nodeData);
    System.out.println(Node3.nodeData);
    //Display pointers
    System.out.println("Hi this is Node2 ==============>:"+Node2);
    System.out.println("This is the value of pointer of Node1:"+Node1.pointer);
    System.out.println("Hi this is Node3===============>:"+Node3);
    System.out.println("This is the value of pointer of Node2:"+Node2.pointer);
    }//main
    }//class
    /***** OUTPUT ***** OUTPUT ***** OUTPUT ***** OUTPUT *****
    Hi i am data contained in Node 1.
    Hi i am data contained in Node 2.
    Hi i am data contained in Node 3.
    Hi this is Node2 ========================>:myList@16f0472
    This is the value of pointer of Node 1 ==>:myList@16f0472
    Hi this is Node3 ========================>:myList@18d107f
    This is the value of pointer of Node 2 ==>:myList@18d107f
    Press any key to continue...
    Thank you very much,
    JMelsi

    Happy to advise. Here we go. :)
    Firstly, you'll want to post your code in code tags. They make your code more legible, thus making it easier and therefore more likely that someone responds. ;)
    Second, it would be more appropriate for class names (such as "myList") to start with an upper-case letter (such as "MyList"). Additionally, the class in question does not represent a whole list but instead a node, so you might want to call it "MyListNode" or something similar.
    Strictly speaking, your code is definitely that of a linked list of nodes. For example, one could print all of the contents in your list with code like this:
    myList node = ...; // assign to the first node
    while (node!=null) // as long as there is a node
        System.out.println(node.nodeData); // print the data in this node
        node = node.pointer; // move on to the next node
    }Note that, in the above code, I didn't have to know how many nodes were in your list or have any references to them beforehand. :) That's the power in the data structure you're creating.
    Enjoy!

  • Linked List Node assigning

    I have a binary B+tree.
    I have done all the insertion..but I have a major problem as my current node is poiting to the last node I inserted node ...
    In the class I have a parent node
    I want to use this to go back to the root...but I fail..function is called from a tree class
    in the function {
    Node curr = this;
    Node temp= this.parent;
    while(temp!=null) {
    temp= temp.parent;
    if(temp!=null) {
    curr=temp;
    return curr;
    However, this code doesn't work...
    not sure why...
    can anyone help me with this .. Thanks?

    carl33p wrote:
    Might have to fill it manually unless anyone else has an idea.
    ...I have a few ideas:
    - keep the logic from getting input from a user separate from your linked list
    class: it is not the responsibility of a linked list to perform such tasks;
    - create a separate class with a main method that instantiates a linked list
    and gets the user input;
    - don't name one of your classes the same as one of Java's "core" classes. When
    you do "import java.util.*" you might get in trouble. Since you are only storing
    int's in your list, a better name would be "IntLinkedList"
    - create a method called add(int) that is responsible for the addition of new
    nodes;
    - create a private inner class for your Node class: you won't be needing this
    Node outside of your IntLinkedList class, so there's no need for it to be
    "visible" for other classes.
    Here's a skeleton:
    class Test {
        private static int getUserInput() {
            // Prompt the user to enter an integer and when
            // a valid integer is entered, return it.
            return -1;
        public static void main(String[] args) {
            IntLinkedList myList = new IntLinkedList();
            int nodeCount = 5;
            while(nodeCount-- > 0) {
                int input = getUserInput();
                myList.add(input);
            System.out.println("myList = "+myList.toString());
    class IntLinkedList {
        private Node start;
        public IntLinkedList() {
            start = null;
        public void add(int value) {
            Node newNode = new Node(value);
            // Your code here
            // - what to do when 'start' equals null?
            // - and what to do when 'start' does not equal null?
        // more methods
        private class Node {
            int value;
            Node next;
            Node(int v) {
                value = v;
                next = null;
            // more methods
    }

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

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

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

  • Can't see the ESS Additional Personal Data link within Personal Information

    Hi All,
    For some reasons, I can not see the Additional Personal Data link within the ESS Personal Information iView. I have checked the Homepage framework and the existence of the iView in the PCD and everything appears to be fine.
    Do I need to assign any additional infotype to my id or give myself specific authorisations to see this link?
    I would really appreciate if you could provide an answer to my query.
    Thanks,
    Vibhu

    Hi,
    I think mostly you have maintained the data in PA30 Transaction and had data in Info type 0105.
    After this try to check with your EA-HR patch and SAP HR patch in the services. If  both are not maintained at the same patch levels such type of problems will occur.
    Regards,
    kishore.

  • After Delete in Linked list...unable to display the linked list

    Hi...i know that there is an implementation of the class Linked Link but i am required to show how the linked list works in this case for my project...please help...
    Yes..I tried to delete some objects in a linked list but after that i am not able to display the objects that were already in the linked list properly and instead it throws an NullPointerException.
    Below shows the relevant coding for deleting and listing the linked list...
    public Node remove(Comparator comparer) throws Exception {
         boolean found = false;
         Node prevnode = head;          //the node before the nextnode
         Node deletedNode = null;     //node deleted...
         //get next node and apply removal criteria
         for(Node nextnode = head.getNextNode(); nextnode != null; nextnode = nextnode.getNextNode()) {
              if(comparer.equals(nextnode)) {
                   found = true;
                   //remove the next node from the list and return it
                   prevnode.setNextNode(nextnode.getNextNode());
                   nextnode.setNextNode(null);
                   deletedNode = nextnode;
                   count = count - 1;
                   break;
         if (found) return deletedNode;
         else throw new Exception ("Not found !!!");
    public Object[] list() {
         //code to gather information into object array
         Node node;
         Object[] nodes = new Object[count];
         node = head.getNextNode();
         for (int i=0; i<count; i++) {
              nodes[i] = node.getInformation();  // this is the line that cause runtime error after deleting...but before deleting, it works without problem.
              node = node.getNextNode();
         return nodes;
    }Please help me in figuring out what went wrong with that line...so far i really can't see any problem with it but it still throws a NullPointerException
    Thanks

    OK -- I've had a cup and my systems are coming back on line...
    The problem looks to be the way that you are handling the pointer to the previous node in your deletion code. Essentially, that is not getting incremented along with the nextNode -- it is always pointing to head. So when you find the node to delete then the line
       prevnode.setNextNode(nextnode.getNextNode());will set the nextNode for head to be null in certain situations (like if you are removing the tail, for instance).
    Then when you try to print out the list, the first call you make is
    node = head.getNextNode();Which has been set to null, so you get an NPE when you try to access the information.
    Nothing like my favorite alkaloid to help things along on a Monday morning...
    - N

  • Problem with Queue and linked list

    Hi... i've got an assignment it start like this.
    You are required to write a complete console program in java includin main() to demonstrate the following:
    Data Structure: Queue, Priority Queue
    Object Involved: Linked-List, PrintJob
    Operations Involved:
    1. insert
    2. remove
    3. reset
    4. search
    Dats all... I've been given this much information... Can any1 try to help me please... How to make a start??? And wat does the print job means???
    Can any1 tell me wat am supposed to do...

    Hi,
    Why don't you start your demo like this?
    import java.io.IOException;
    public class Demo {
         public Demo() {
         public void startDemo() throws IOException {
              do {
                   System.out.println("String Console Demo ");
                   System.out.println("\t" + "1. Queue Demo");
                   System.out.println("\t" + "2. PriorityQueue Demo");
                   System.out.println("\t" + "3. LinkedList Demo");
                   System.out.println("\t" + "4. PrintJob Demo");
                   System.out.println("Please choose one option");
                   choice = (char) System.in.read();
                   showDemo(choice);
              } while (choice < '1' || choice > '4');
         public void showDemo(char ch) {
              switch (ch) {
              case '1':
                   System.out.println("You have chosen Queue Demo ");
                   showOperations();
                   break;
              case '2':
                   System.out.println("You have chosen Priority Queue Demo ");
                   showOperations();
                   break;
              case '3':
                   System.out.println("You have chosen LinkedList Demo ");
                   showOperations();
                   break;
              case '4':
                   System.out.println("You have chosen Print Job Demo ");
                   showOperations();
                   break;
         private void showOperations() {
              System.out.println("Please choose any operations ");
              System.out.println("\t" + "1. Insert ");
              System.out.println("\t" + "2. Remove ");
              System.out.println("\t" + "3. Reset ");
              System.out.println("\t" + "4. search ");
         public static void main(String[] args) throws IOException {
              Demo demo = new Demo();
              demo.startDemo();
         private char choice;
    Write a separate classes for the data structures show the initial elements and call the methods based on the operations then show the result.
    Thanks

  • 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

  • Can I import my old link lists into 365 site?

    Hi I would like to import all my hard work from my old 2010 sharepoint site into the new 365 site.
    I exported my links to excel but I cannot see an import option on a link list in 365.
    Surely there must be an easy way to do this that I am missing?
    thanks

    Below are the steps to save List as Template:
    >> Go to the List - List Settings - Click on Save List as Template - Provide Template Name and make sure you check the "With Content" box available on the page. 
    Once the List is successfully saved as template, you will find the template under List Templates gallery. Download that template it should have ".stp" extension. Get that file and upload the file to List Templates gallery of your SharePoint Online Office
    365 site. Then create a new app and there you should find the Template and create a list using that template.
    If you have any questions then let me know.
    Please ensure that you mark a question as Answered once you receive a satisfactory response.

Maybe you are looking for

  • Company Webmail Outlook Web Access

    When I'm on a biz trip I have to use Web Access for my webmail. I noticed that when I use Safari vs. when I use my PC lap top, the whole look is very different. PC allows me to have a preview page and on my ibook it constantly asks for my password. A

  • Adobe Photoshop CS3 from Windows Vista to Windows 8 Product Key Invalid

    Hi, I switched my OS from Windows Vista to Windows 8.1 (Clean installation). On Windows Vista, I was running a trial version and tried my product key but it didnt work. On Windows 8.1 also, the product key didn't work. Now I can't check my version be

  • TS3433 anyone using extended wifi on TimeCapsule 7.6.1 fw with BT router

    Just updated the firware on my TC to 7.6.1 and I now have problems with the TC wifi configured to extend the wifi from my BT router. These include flashing amber light on the TC, amber connection to the Internet in Airport Utility and general access

  • How to configure EAP-TLS OTA

    Hello, I am trying to configure wi-fi setting OTA on iPhone/iPad.  The certificate enrolment goes thru fine and the device signs the final request with newly acquired certificate. I am stuck in the last phase i.e. pushing the final mobileconfig conta

  • BAPI or FM to Update storage location in outbound delivery with many items

    Hello! I have an urgent problem. Storage location determination didn't work and were  created thousands of deliveries without storage location. We want to run LSMW using BAPI. Which BAPI can update storage location (for many items in delivery. We saw