Recursion using a linked list

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

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

Similar Messages

  • Why LinkedList uses doubly linked list and not single link list

    Hi,
    Please help me to understand the concept behind java using doubly linked list for LinkedList and not single link list?
    Edited by: user4933866 on Jun 26, 2012 11:22 AM
    Edited by: user4933866 on Jun 26, 2012 11:25 AM
    Edited by: EJP on 27/06/2012 08:50: corrected title to agree with question

    EJP wrote:
    Could you help me with one real world use case where we need to traverse linklist and arraylist in backward direction other than printing the linklist or arraylist in reverse order. One example is that you might want to use it as a stack. For a very large (+very+ large) stack it would out-perform the Vector-based Stack in the API.The first thing that pops into my head is an undo/redo function for a text editor. Each edit action is dumped onto such a stack. Each time you hit CTRL+Z to undo an action you go back in the stack. Each time you hit CTRL+Y to redo the action you go forward again.

  • How to use circular linked list in pl/sql?

    Hi all,
    how to use the circular linked list on pl/sql programming.
    thanks in advance
    Rgds,
    B@L@

    d balamurugan wrote:
    Hi,
    I needed this concept for the below example
    TABLE_A have the columns of
    ID COL_1 COL_2 COL_3 COL_4 COL_5 COL_6 COL_7
    1....Y.........N........N.........Y........ N........N........ N
    2....N.........N....... N.........Y.........N........N.........Y
    in the above data
    for id 1 i will need to take the value for COL_4, then i will check the next availability of Y through out through out the remaining columns, so next availability is on COL_1 so, i need to consider COL_4 which already Y and also i need to consider COL_5, COL_6, COL_7 as Y.
    for id 2 if i need COL_7 then i need to come back on circular way and need to check the next availability of Y and need to take the columns having N before the next availability of YAnd... even after all that description... you haven't given any indication of what the output should look like.
    Taking a wild guess on my part... something like this would do what you appear to be asking...
    SQL> ed
    Wrote file afiedt.buf
      1  with t as (select 1 as id, 'Y' as col1, 'N' as col2, 'N' as col3, 'Y' as col4, 'N' as col5, 'N' as col6,'N' as col7 from dual union all
      2             select 2, 'N', 'N', 'N', 'Y', 'N', 'N', 'Y' from dual)
      3  --
      4  -- END OF TEST DATA
      5  --
      6  select id
      7        ,rcol
      8        ,case when instr(cols,'Y',rcol+1) = 0 then instr(cols,'Y')
      9              else instr(cols,'Y',rcol+1)
    10         end as next_Y_col
    11  from   (select id, rcol, col1||col2||col3||col4||col5||col6||col7 as cols
    12          from t, (select &required_col as rcol from dual)
    13          where id = &required_id
    14*        )
    SQL> /
    Enter value for required_col: 4
    old  12:         from t, (select &required_col as rcol from dual)
    new  12:         from t, (select 4 as rcol from dual)
    Enter value for required_id: 1
    old  13:         where id = &required_id
    new  13:         where id = 1
            ID       RCOL NEXT_Y_COL
             1          4          1
    SQL> /
    Enter value for required_col: 7
    old  12:         from t, (select &required_col as rcol from dual)
    new  12:         from t, (select 7 as rcol from dual)
    Enter value for required_id: 2
    old  13:         where id = &required_id
    new  13:         where id = 2
            ID       RCOL NEXT_Y_COL
             2          7          4
    SQL>If that's not what you want... then it's time you started learning how to ask questions properly.

  • A queue using a linked list..having troubles with the rest

    ok...
    this is the assignment ( [http://jessehardesty.com/uploads/p2.JPG] ) picture is kind of big...
    I have to have a "queue" class, but I will have to remove some people from the line that are in the middle (which is why i put it in quotes).
    this is the queue class I have as of now...
    public class Queue
           private static class Node
              int item;
              Node next;
           private Node head = null;  // Points to first Node in the queue.
                                      // The queue is empty when head is null.
           private Node tail = null;  // Points to last Node in the queue.
           void enqueue( int N ) {
                 // Add N to the back of the queue.
              Node newTail = new Node();  // A Node to hold the new item.
              newTail.item = N;
              if (head == null) {
                    // The queue was empty.  The new Node becomes
                    // the only node in the list.  Since it is both
                    // the first and last node, both head and tail
                    // point to it.
                 head = newTail;
                 tail = newTail;
              else {
                    // The new node becomes the new tail of the list.
                    // (The head of the list is unaffected.)
                 tail.next = newTail;
                 tail = newTail;
           int dequeue() {
                  // Remove and return the front item in the queue.
                  // Note that this can throw a NullPointerException.
              int firstItem = head.item;
              head = head.next;  // The previous second item is now first.
              if (head == null) {
                    // The queue has become empty.  The Node that was
                    // deleted was the tail as well as the head of the
                    // list, so now there is no tail.  (Actually, the
                    // class would work fine without this step.)
                 tail = null;
              return firstItem;
           boolean isEmpty() {
                  // Return true if the queue is empty.
              return (head == null);
        }my problem is that I don't know how to go about doing the units of time. We are given a data file with the time of arrival, length of transaction, amt bought, and money spent.
    it's kind of long or I'd post it...but they are all ints. I'll have to read from the file. My problem (for now) is that I don't know what kind of loop to do, and how to read them in correctly...it is 4 ints per line in the file, spaces in between of course. What kind of loop should be used?...and how do I go about keeping track of all the "people" in line without using 40+ counters (one for each "person").
    thanks, and hopefully that makes some sense.
    Edited by: Taco_John on Mar 23, 2008 5:08 PM

    * Queue.java
    * Created on March 24, 2008, 3:12 PM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package test;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Scanner;
    * @author Rajesh
    public class Queue <T>
    private static class Node<T>
    int item;
    int custArrive;
    int transTime;
    int amtBought;
    int dollSpent;
    Node next;
    private Node head, tail;
    private int count;
    public Queue()
    count = 0;
    head = tail = null;
    public void enqueue( T element ,int a,int b,int c,int d) {
    // Add N to the back of the queue.
    Node<T> newTail = new Node<T>(); // A Node to hold the new item.
    if (head == null)
    head = newTail;
    head.custArrive = a;
    head.transTime = b;
    head.amtBought = c;
    head.dollSpent = d; tail = newTail;
    else
    tail.next = newTail;
    tail = newTail;
    tail.custArrive = a;
    tail.transTime = b;
    tail.amtBought = c;
    tail.dollSpent = d;
    private int dequeue()
    int firstItem = head.item;
    head = head.next; // The previous second item is now first.
    if (head == null)
    tail = null;
    return firstItem;
    public void showElement()
    Node<T> newTail = new Node<T>();
    for(newTail=head; ;newTail=newTail.next)
    System.out.println(""+newTail.custArrive+"\t"+newTail.transTime+"\t"+newTail.amtBought+"\t"+newTail.dollSpent);
    if(newTail == tail)
    break;
    *}* boolean isEmpty()
    // Return true if the queue is empty.
    return (head == null);
    public static void main (String [] args)throws IOException
    int custArrive;
    int transTime;
    int amtBought;
    int moneySpent;
    FileReader infile = new FileReader ("C:/Documents and Settings/pb46627/Desktop/prog3.txt");
    Scanner fin = new Scanner (infile);
    Queue myQueue = new Queue();
    int i=0;
    while (fin.hasNextInt())
    custArrive = fin.nextInt();
    transTime = fin.nextInt();
    amtBought = fin.nextInt();
    moneySpent = fin.nextInt();
    myQueue.enqueue(i++,custArrive,transTime,amtBought,moneySpent);
    *//fin.next();*
    i++;
    myQueue.showElement();
    *// System.out.println(""+myQueue.count);*
    And this is the Input file i used.......
    10     20     30     40
    50     60     70      80
    90     100     110     120
    prog3.txt
    Now you can able to see the output as
    10     20     30     40
    50     60     70      80
    90     100     110     120
    i use BOLD FONT_ , indicates my changes
    just try with this and comment.......
    i'm waiting for your reply.....
    thank you
    rajesh

  • Recursively Finding a Node in a Linked List

    I'm trying to find a node recursively in this linked list but keep coming up with an error message - can anyone tell me what is wrong?
         public boolean find (Object obj)
              DonorNode node = new DonorNode(obj);
              DonorNode current = list;
              if (don.equals(current))
                   return true;
              else
                   return find(current.next);
         }

    Please post within code tags (button above the message box).
    Without more information it's hard to say.
    What is list?
    What is don?
    If you don't mind me pointing out:
    A method named find conventionally returns some object it is searching for or null if not found.
    What you have (by that I mean a method returning boolean) is generally named contains (or some other obvious predicate name).
    That being said, if I assume that DonorNodes contain some Object and have getter functions to access those; and that list is a DonorNode representing the head of the list, try something like:public boolean contains(Object o) {
        return contains(o, list);
    private boolean contains(Object o, DonorNode n) {
        if (n.getObject() == o)
            return true;
        if (n.getNext() == null)
            return false;
        return contains(o, n.getNext());
    }Although keep in mind that comparing two Objects using '==' will result in reference only comparison. If you need some other form of comparison you might consider using the equals method (make sure you then implement it in all potentially contained classes) or even narrowing the accepted argument to classes that implement the Comparable interface.
    Hope this helps.

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

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

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

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

  • Errors executing bulk query when updating a Sharepoint Linked List from Access

    Hi all,
    I have a Sharepoint list that is a Linked List with MS Access. It has just under 5,000 items (4,864), thus meaning it avoids the reduction in functionality lists of greater than 5,000 items have.
    Among the list are five calculated columns. These take the information from another column (different employee numbers), and by using a formula produce a clickable link to my company's Directory page, where that particular employee's info is displayed. I'm
    not sure if these five columns are relevant to my query, but I'm mentioning them in case.
    My problem is this: Frequently when I run any query on the list that updates the list, I get this error: "There were errors executing the bulk query or sending the data to the server. Reconnect the tables to resolve the
    conflicts or discard the pending changes".
    When I review the errors, it says they conflict with errors a previous user made (with that previous user being me). It frequently highlights several columns, despite the info in them being identical, and the calculated columns (with the original showing
    the value they contained and the new showing #VALUE! (as Access can't display the formulas).
    However, if I click Retry All Changes, all the update stick and everything seems fine. Why is this happening? It's proving very annoying and is really stopping the automation of my large number of queries. A list of 5000 items isn't particular big (and they've
    got roughly 100 columns, although I didn't think that was too large either, given Excel's 200+ column limit).
    Is this due to poor query design and SQL? Is this due to connectivity issues (which I doubt, as my line seems perfect)? Is this due to Access tripping over itself and not executing the update on each row in the table, but rather executing them concurrently
    and locking itself up? I'm at wit's end about it and really need to get this sorted.
    Thanks in advance for any suggestions.

    Hi amartin903,
    According to your description, my understanding is that you got an error when you used a linked list from Access.
    The table that you are updating is a linked table that does not have a primary key or a unique index. Or, the query or the form is based on a linked table that does not have a primary key or a unique index. Please add the primary key or a unique index.
    Here is a similar post, please take a look at:
    http://social.technet.microsoft.com/Forums/en-US/545601e9-a703-4a02-8ed9-199f1ce9dac8/updating-sharepoint-list-from-access?forum=sharepointdevelopmentlegacy
    I hope this helps.
    Thanks,
    Wendy
    Wendy Li
    TechNet Community Support

  • How do you change the font in WPC Link List Header ...

    Does any one know how/where to change the font in Web Page Composer on the Link List Header?  I am using the Link List header delivered with the product. 
    It looks like it is pulling arial font but we are adding content in a different font in the paragraphs and want the fonts to be the same.  Is there something I can change in the theme?
    thanks
    Angie.

    You need to go to the
    Content Adminstration/KM Content/etc/wpceditor/css/runtime  and look in the sdn_general.css file.  The controls are all there.  You can rename or create a new style sheet as this will modify all WPC sites.

  • Sorting linked lists - Help

    I am writing a program for an assignment that reads a file containing population growth for all the Counties in the U.S. I'm required to use a link list to store the data. They want me to sort the data based on certain criteria. My first problem is that as each new County instance is created, it is to be inserted into this linked list in alphabetical order first by county name.
    My understanding of linked lists is that they cannot be randomly accessed like a vector or an array. So is it possible to do this without using a vector or an array? And how would I go about it?
    thanks.

    Can you create a second, sorted linked list?The prof. didn't specify whether or not I can use a second list.
    Are you prohibited from using the collections framework (probably, if it is a school assignment!)Not really sure on this one. Again it is not specified in the assignment
    (Why would they have you store this data in a linked list??)I their reasoning is to have us learn how to implement linked list because it can grow or shrink when necessary.(Other than that I don't understand the practicality of it either)
    Are you using a doubly linked list (forwards and backwards)?The assignment does not specify a certain linked list to use.
    Did your prof mention any sort algorithms you might use? He states later in the assignment that I have to generate different growth reports by using MergeSort.
    I appreciate your help and comments. Unfortunately my prof. is very vague about the assignment and its implementation in his outline. He just kind of throws us into it hoping that we will figure it out.

  • Faster way to search linked list?

    I'm pretty new to programming and I have to write a kind of psuedo implementation of a cache using a linked list (has to be a linked list). The problem is when I'm setting the maximum size of the linked list to a high number (like 2000), it goes incredibly slow. I don't know how I can make this faster.
    Here are the 2 main methods I'm using for it:
    public void addObject(Object toAdd){
         cacheList.addFirst(toAdd);
         if(cacheList.size()>=maxAllowedSize){
              removeObject(maxAllowedSize-1);
    public boolean containsObject(Object toFind){
         boolean test=false;
         for(int x=0;x<cacheList.size();x++){
              if(toFind.equals(cacheList.get(x))){
                   test=true;
                   hits++;
                   removeObject(x);
                   addObject(toFind);
                   x=cacheList.size(); //ends for loop
         total++;
         return test;
    }Where maxAllowedSize is a command line argument and removeObject just calls cacheList.remove(index).
    For testing, I'm using a text file with something over 1.3 million words and using scanner to read them. Here is the code that calls the two methods:
    if(!cache.containsObject(currentWord)){
         cache.addObject(currentWord);
    }Since containsObject adds the word itself, this calls addObject if the word isn't found (added to the front of the list).
    Any help is greatly appreciated.

    darkambivalence wrote:
    Linked list is what was specified in my assignment.
    Then to be honest I expect that part of the learning of assignment is to see how a LinkedList is a poor choice for a list that you want to search.
    Why will that run poorly? Because what do you think remove is doing? The remove has to search to find the thing you want to remove. So it's doing that search twice. So it will be twice as slow.
    There really isn't much you can do to make this faster. LinkedLists are great for many reasons but "random" accessing (for searching for example) is not one of them. I suppose if one really wanted to squeeze out performance you could keep the list sorted. So when inserting insert into the "right" place in the list and then as you search if a value would fall in between two buckets and doesn't exist in your list you can stop there. A doubly linked list would probably help for this implementation.
    In the real world though you would either not use a LinkedList at all or a Map depending on the needs.

  • Links List iView: Hiding the "Organize Entries" Command

    Hi all!
    I am using the Links List iView to display some corporate links. This iView shows an "Organize Entries" control to update the list by default. However, in my requirement, i need to hide this command from the end user. I have taken a look on the Layout Sets involved and have not found this control; Also, i've seen on the Help System that if i change the permissions on the folder, the iView hides this control, but i've tried that and it didn't work.
    Do you know how can i hide this control?
    Thanks for your help!
    Regards,
    Thiago

    Hi Thiago,
    I am not sure if I understood your question correctly.
    When you click on 'Advanced Copy', you have several options: you can add a prefix or a suffix to the name of the LayoutSet or you can replace a prt of the name. You can find more information on this issue on help.sap.com: http://help.sap.com/saphelp_nw04/helpdata/en/30/562cbf45c5b440a2885877a1c230d5/frameset.htm
    Is this what you have been looking for?
    Kind reagrds
    Karin

  • Baffling linked list error in C program

    I've been working at porting some programs over to a Mac that were built using MS C 6.0.  One of the programs uses a linked list to hold some data.  Just couldn't get it to work.  So I decided to run a really simple test.  Create a short linked list and then print out the list.
    The code is below and the output is below that.  It looks like all the nodes get created properly and pointers assigned correctly but when I print out the list it crashes after the second node everytime.  It appears that in node 2 the link to the next node has been corrupted but I can't see anywhere that happens.  Is this not the way xcode does linked lists?
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <math.h>
    struct linklist {
        int node_number;
        char node_name[10];
        struct linklist * next;
    struct linklist * makenode();
    int main(int argc, const char * argv[])
        struct linklist * list_head;
        struct linklist * list_item;
        int i;
        // insert code here...
        printf("Hello, World!\n");
        list_head = makenode();
        list_head->node_number = 1;
        strcpy(list_head->node_name, "node 1");
        list_head->next = NULL;
        list_item = list_head;
        printf("head-> %0lx, item-> %0lx \n", (unsigned long) list_head, (unsigned long) list_item);
        for (i = 1; i < 10; i++)
            list_item->next = makenode();
            printf("New Node %d at %lu\n", i+1, (unsigned long) list_item->next);
            list_item = list_item->next;
            list_item->node_number = i+1;
            sprintf(list_item->node_name, "node %d", i+1);
            list_item->next = NULL;
            printf("list_item points at %lu\n", (unsigned long) list_item);
        list_item = list_head;
        for (i = 0; i < 10; i++)
            printf("list_item -> %lu>\n", (unsigned long) list_item);
            printf("%d - %s>\n", list_item->node_number, list_item->node_name);
            list_item = list_item->next;
        return 0;
    struct linklist * makenode()
        return (struct linklist *) (malloc( sizeof(struct linklist())));
    Output>>>>>
    Hello, World!
    head-> 7fdf604000e0, item-> 7fdf604000e0
    New Node 2 at 140597369256496
    list_item points at 140597369256496
    New Node 3 at 140597369256512
    list_item points at 140597369256512
    New Node 4 at 140597369256528
    list_item points at 140597369256528
    New Node 5 at 140597369256544
    list_item points at 140597369256544
    New Node 6 at 140597369256560
    list_item points at 140597369256560
    New Node 7 at 140597369256576
    list_item points at 140597369256576
    New Node 8 at 140597369256592
    list_item points at 140597369256592
    New Node 9 at 140597369256608
    list_item points at 140597369256608
    New Node 10 at 140597369256624
    list_item points at 140597369256624
    list_item -> 140597369241824>
    1 - node 1>
    list_item -> 140597369256496>
    2 - node 2>
    list_item -> 7306087013738872835>

    Change
    return (struct linklist *) (malloc( sizeof(struct linklist())));
    to
        return (struct linklist *) (malloc( sizeof(struct linklist)));
    Hello, World!
    head-> 100103b10, item-> 100103b10
    New Node 2 at 4296031024
    list_item points at 4296031024
    New Node 3 at 4296031056
    list_item points at 4296031056
    New Node 4 at 4296031088
    list_item points at 4296031088
    New Node 5 at 4296031120
    list_item points at 4296031120
    New Node 6 at 4296031152
    list_item points at 4296031152
    New Node 7 at 4296031184
    list_item points at 4296031184
    New Node 8 at 4296031216
    list_item points at 4296031216
    New Node 9 at 4296031248
    list_item points at 4296031248
    New Node 10 at 4296031280
    list_item points at 4296031280
    list_item -> 4296030992>
    1 - node 1>
    list_item -> 4296031024>
    2 - node 2>
    list_item -> 4296031056>
    3 - node 3>
    list_item -> 4296031088>
    4 - node 4>
    list_item -> 4296031120>
    5 - node 5>
    list_item -> 4296031152>
    6 - node 6>
    list_item -> 4296031184>
    7 - node 7>
    list_item -> 4296031216>
    8 - node 8>
    list_item -> 4296031248>
    9 - node 9>
    list_item -> 4296031280>
    10 - node 10>
    Program ended with exit code: 0

  • Anyone help me please~ many thanks! C++ linked list

    I've written a Microsoft C++ code, using a linked list to store the result which is sent by a device.
    The head node and tail node of linked list is put into a class, and all methods are set to 'static' to manipulate the data inside the linked list. So that different thread can access to it.
    At first, everything runs ok in native environment,( i compile it as a .exe file)....
    However, when I export it into DLL and run inside java code using JNI. The linked list was gone (head node & tail node lost). It seems that JVM try to re-initialize the head node everytime I invoke those method.
    Hence, I modify the class which handle the link list, set all its methods into non-static, and define a global variable. Yet, another problem came out... Acess Violation error... it seems again the adress(pointer) of head node can't be modified...
    Is there any other way to solve this problem?? I mean, I want the head node remains valid for each time of java method is called.

    Too vague.
    If you could show us some relevant Java and JNI C++
    code.
    Please paste your code between code tags exactly like
    this:
    your codeYou may read the [url
    http://forum.java.sun.com/help.jspa?sec=formatting]For
    matting tips for more information.Here you are:
    this is the header definition of the linked list handler, all functions are set to be non-static
    typedef struct DeviceLinkList{
        char *deviceNumber;//device of monitor device
        int result;
        DeviceLinkList *nextNode;
        DeviceLinkList *prevNode;
    } DeviceLinkList;
    class DeviceListHandler
    public:
      DeviceLinkList *headNode = NULL;
      DeviceLinkList *tailNode = NULL; //Moving to last of the entry
      void addNode(char *device); //add monitor device
      void deleteNode(char *device); //remove after device is stop monitorred
      void printAll();
      void setResult(char *device);
    private:
      DeviceLinkList *searchNode(char *device);
    };Here is the implementation of my code in function 'addNode':
    void DeviceListHandler::addNode(char *device)
      printf("Creating Link List.\n");
      printf("Head is %d\n" ,headNode);
      if(headNode != NULL) //create new node from empty --> Access Violation Exception start from here
        DeviceLinkList *temp = new DeviceLinkList;
        temp->deviceNumber = device;
        temp->nextNode = NULL;
        temp->prevNode = tailNode;
        tailNode->nextNode = temp;
        tailNode = temp; //move tailNode point to the last entry
        printf("Connecting to Tail Node done\n");
      else
        DeviceLinkList *temp = new DeviceLinkList;
        printf("Creating Head\n");
        temp = new DeviceLinkList;
        temp->deviceNumber = device;
        temp->nextNode = NULL;
        temp->prevNode = NULL;
        printf(".....DONE...!!!\n");
        headNode = temp;
        tailNode = headNode;
        printf("Finish Head-Tail Node creation\n");
      printf("Creation Done\n");
    }This is the one of function which export to JNI:
    JNIEXPORT void JNICALL Java_PBXdll_monitorStart  (JNIEnv * env, jobject obj, jstring callingdevice)
    char device[MAX_CstaDialingNumber];
    strcpy(device,env->GetStringUTFChars(callingdevice, 0));
    printf("Monitoring device: %s\n", device);
    startMonitor(device);
    deviceList -> addNode(device); // deviceList is the global variable
    }so...when i call the method monitorStart in java... it terminated abnormally with a Access Violation Exception.....the linked list can't be created.

  • Doubly link list question

    I desparately need help with these topic. Currently, I am doing a project using doubly link list data structure and swing components. However, I just could not get the data items of the doubly link list to display on the JTextArea. Is this possible at all or does anybody out there know in anyway to solve this problem?

    Thanks a lot for the timely reply amolk. Here is the sample code you request for:
    //The following code is my Link class:
    import java.io.Serializable;
    public class Link implements Serializable
    public String dTitle, dPublisher, dCategory, dUserlevel, dDescription, dISBN, dDay, dMonth, dYear;
    public float dPrice;
    public int dQuantity;
    public Link next; // next link in list
    public Link previous; // previous link in list
    public Link(String tit, String pub, String cat, float price, int qty, String ISBN, String day, String month, String year, String level, String des) // constructor
    dTitle = tit;
    dPublisher = pub;
    dCategory = cat;
    dPrice = price;
    dQuantity = qty;
    dISBN = ISBN;
    dDay = day;
    dMonth = month;
    dYear = year;
    dUserlevel = level;
    dDescription = des;
    public void displayLink()
    System.out.println(dTitle + "");
    } // end class Link
    //The following is the actual doubly link list code
    import java.io.Serializable;
    public class DoublyLinkedList implements Serializable
    public String back;
    public boolean notFound = false;
    private Link first; // ref to first item
    private Link last; // ref to last item
    public DoublyLinkedList() // constructor
    first = null; // no items on list yet
    last = null;
    public boolean isEmpty() // true if no links
    return first==null;
    public void insertFirst(String title, String publisher, String category, float price, int quantity, String ISBN, String day, String month, String year, String userlevel, String description) // insert at front of list
    Link newLink = new Link(title, publisher, category,price, quantity, ISBN, day, month, year, userlevel, description); // make new link
    if( isEmpty() ) // if empty list,
    last = newLink; // newLink <-- last
    else
    first.previous = newLink; // newLink <-- old first
    newLink.next = first; // newLink --> old first
    first = newLink; // first --> newLink
    public Link deleteFirst() // delete first link
    {                              // (assumes non-empty list)
    Link temp = first;
    if(first.next == null) // if only one item
    last = null; // null <-- last
    else
    first.next.previous = null; // null <-- old next
    first = first.next; // first --> old next
    return temp;
    public void displayForward()
         System.out.println("first --> last): ");
    Link current = first; // start at beginning
    while(current != null) // until end of list,
    current.displayLink(); //display data
    current = current.next; // move to next link
    System.out.println("");
    //Hoping to hear from you soon.

Maybe you are looking for