Recursion:returning the largest value in a linked list

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

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

Similar Messages

  • Finding the largest value...

    Hi guys,
    I'm creating a method where it finds the largest value in a list of integers, using a loop. When it finds it, it's stored in the "max" and returns the "max".
    Here's the code...
        public Integer findMax()
            List<Integer> list = Arrays.asList(4,8,2,10,24);
            int max = 0;
            for(Integer i = 0 ; i < list.size() ; i++) {
                if(max == list.get(i))
                max = i;
            return max;
        }It complies, but when i run it, it doesn't actually get the largest value (which should be 24). It's still 0 when i Inspect it.
    Does anybody know where i'm going wrong with this?

    Well i went through the method and it seems to be printing 0 five times...
        public Integer findMax()
            List<Integer> list = Arrays.asList(4,8,2,10,24);
            int max = 0;
            for(Integer i = 0 ; i < list.size() ; i++) {
                if(max >= list.get(i))
                max = list.get(i);
                System.out.println(max);
            return max;
        }After looking looking through the API, i used the length, instead of size, but when i compile the program it says it can't find the method. Do you know what else i have to change or add in the code for it to compile?
    DrClap wrote:
    if(max == list.get(i)) Can you explain, in words, what this comparison was meant to do?I've edited that, because that's wrong.

  • Function to return the Entry Value based on Assignment, Element and Date

    Hi Guys,
    Is there a function that returns the Entry Value for the Assignment Element, based on the Assignment Number, Element Name, Entry Segment and the End of Period date?
    Example:
    ==============
    Input Parameters:
    Employee: Iana
    Assignment Num: 123
    Element: D480
    Element Entry: Fund Name
    Output Parameter:
    Element Entry Value: MLC Super Fund
    Thanks,
    Iana

    For element entry values you can use:
    select petf.element_name, nvl(peevf.screen_entry_value,0) screen_entry_value
    from
    pay_element_entries_f peef, pay_element_types_f petf,
    pay_element_entry_values_f peevf, pay_input_values_f pivf,
    per_all_assignments_f paaf
    where petf.element_type_id = peef.element_type_id
    and :p_date_earned between pivf.effective_start_date and pivf.effective_end_date
    and :p_date_earned between petf.effective_start_date and petf.effective_end_date
    and peevf.input_value_id = pivf.input_value_id
    and paaf.assignment_id = peef.assignment_id
    and petf.business_group_id = :p_business_group_id
    and peevf.element_entry_id = peef.element_entry_id
    and :p_date_earned between peef.effective_start_date and peef.effective_end_date
    and :p_date_earned between peevf.effective_start_date and peevf.effective_end_date
    and :p_date_earned between paaf.effective_start_date and paaf.effective_end_date
    and pivf.name = :p_input_value_name
    and petf.element_name = :p_element_name
    and peef.entry_type = 'E'
    and peevf.effective_start_date = peef.effective_start_date
    and peevf.effective_end_date = peef.effective_end_date
    --and peef.assignment_id = :p_assignment_id
    and paaf.assignment_number = :p_assignment_number;
    For payroll results you can use:
    select sum(prrv.result_value)
    from pay_run_results prr, pay_run_result_values prrv,
    pay_assignment_actions paa, pay_payroll_actions ppa,
    pay_element_types_f petf, pay_input_values_f pivf,
    per_all_assignments_f paaf, per_all_people_f papf
    where
    petf.element_type_id = pivf.element_type_id
    and :p_pay_date between petf.effective_start_date and petf.effective_end_date
    and :p_pay_date between pivf.effective_start_date and pivf.effective_end_date
    and paa.assignment_action_id = prr.assignment_action_id
    and petf.element_type_id = prr.element_type_id
    and ppa.payroll_action_id = paa.payroll_action_id
    and prrv.input_value_id = pivf.input_value_id
    and prr.run_result_id = prrv.run_result_id
    and petf.element_name = :p_element_name
    and pivf.name = :p_input_value_name
    and ppa.date_earned = :p_pay_date
    and papf.person_id = paaf.person_id
    and nvl(prr.start_date,ppa.effective_date) between paaf.effective_start_date and paaf.effective_end_date
    and nvl(prr.start_date,ppa.effective_date) between papf.effective_start_date and papf.effective_end_date
    and paaf.assignment_id = paa.assignment_id
    and papf.employee_number = :p_employee_number;

  • Return Into.  Can I return the old value in an update statement?

    Hello - I have an update statement and I need the value of a field, prior to the update. Is it possible to use the Return Into to do this? Or do I have to have a separate select statement prior to the update statement in order to store that value in a variable?
    Thanks!

    RETURNING INTO is valid for an UPDATE, but it returns the new value, not the old value.
    SCOTT @ nx102 Local> select * from a;
          COL1
             4
    Elapsed: 00:00:00.00
    SCOTT @ nx102 Local> ed
    Wrote file afiedt.buf
      1  declare
      2    l_old_col1 number;
      3  begin
      4    update a
      5       set col1=col1+1
      6     returning col1 into l_old_col1;
      7    dbms_output.put_line( l_old_col1 );
      8* end;
    SCOTT @ nx102 Local> /
    5
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:00.00If you are trying to track historical changes, have you looked at Workspace Manager? That can be far easier than writing your own change tracking code...
    Justin

  • Finding the largest values of an array without using if condition

    Hi,
    I am trying to find the largest values of an array without using any if condition. Can any one tell me the solution for that..
    Thanks

    I am trying to find the largest values of an arrayThe 'S' to values suggests that you want not only the largest one, but multiple ones among the largest ones. The best way, I think, is to sort the array, so that its largest values are grouped topgether. If the type is already Comparable, the following single line does the job:
    Collections.sort(myArray);After this, the last values of the array are the largest ones.
    Jerome.

  • How do I return the displaysleep value from the console?

    I know that I can do pmset -g to list all the settings, including displaysleep, but I  was hoping there was a command similar to that for the screensaver which only returns the numerical value:
    defaults -currentHost read com.apple.screensaver idleTime
    Any possibility there is a console function that will return the value only?
    Thanks.

    Hi RavensFan,
    Thank you for your help.
    I have seen this Max/Min function, and I tried it, but I get an error becuase my signal is apprently "dynamic data" and the max/min function accepts double precision data, so thats the problem I am encountering at this moment. I have modified the block diagram to convert the "dynamic data" into a double and then do the same thing you suggested, but I will test it tomorrow in the lab. 
    I am currently working around this by using a numeric input, which the user would simply watch the sensor output over the calibration period and manually input that value into the formula.
    Thanks again!
    PackersFan btw...
    Cheers

  • The Popup dialog Page needs two times to return the selected value[10.1.3]

    Hi All,
    I have problem in an JSF Application that uses the EMP and DEPT tables .
    the Application contains two pages
    page 1 : a calling page uses EmpView as ADF Table .
    page 2 : a popup List of Values (LOV) dialog page uses DeptView
    These cause the popup dialog page to return to the calling page and to set the selected value into the Deptno attribute .
    the calling page includes :deptno and dname columns as
    <af:column headerText="#{bindings.EmpView1.labels.Deptno}">
    <af:selectInputText value="#{row.Deptno}"
    required="#{bindings.EmpView1.attrDefs.Deptno.mandatory}"
    columns="#{bindings.EmpView1.attrHints.Deptno.displayWidth}"
    action="dialog:ChooseDept1" id="deptnoField"
    autoSubmit="true">
    <f:convertNumber groupingUsed="false"
    pattern="#{bindings.EmpView1.formats.Deptno}"/>
    </af:selectInputText>
    </af:column>
    <af:column headerText="#{bindings.EmpView1.labels.Dname}">
    <af:inputText value="#{row.Dname}" simple="true"
    required="#{bindings.EmpView1.attrDefs.Dname.mandatory}"
    columns="#{bindings.EmpView1.attrHints.Dname.displayWidth}"
    partialTriggers="deptnoField" autoSubmit="true"/>
    </af:column>
    and popup dialog page includes : Submit Button to return selected value to calling page :-
    <af:tableSelectOne text="Select and">
    <af:commandButton text="Submit">
    <af:returnActionListener value="#{row.Deptno}"/>
    <af:setActionListener from="#{row.Deptno}"
    to="#{bindings.Deptno.inputValue}"/>
    </af:commandButton>
    </af:tableSelectOne>
    the problem is
    I have to press ( two times ) the select button in the calling page to
    return the selected value into the Dname attribute .
    best regards,

    Hi,
    However, I am using the Jdeveloper 10.1.3.3, but still getting this error. I could not find any threads related to this problem and hence I wrote up here. Anyway I have also logged an SR #7179012.993 for the same with the testcase. I hope the issue will be resolved soon.
    Thanks,
    Neeraj

  • GUID generation issue, SYSUUID always returns the same value.

    Hi,
    I'm using "SELECT SYSUUID FROM DUMMY" to get a guid value but it always return the same value.
    What should I do to get a unique value each time I execute the query above.
    Thanks.

    I thought I had the same problem and I found that if you generate multiple UUID's in the same SQL, it they will be the same.  If you make multiple calls, you should get multiple UUID's. 
    Try this:
    SELECT SYSUUID as UUID1 FROM DUMMY;
    SELECT SYSUUID as UUID2 FROM DUMMY;
    I get the following results:
    UUID1 = 538632FD7EA20426E10000000A3F10A9
    UUID2 = 538632FE7EA20426E10000000A3F10A9
    Notice that the strings look almost identical, but the 8th character on UUID1 is a D and the 8th on UUID2 is a E.
    Jim

  • How to read the selected value of a dropdown list box

    Hello,
    I have 2 custom fields which are of type dropdown list on Accounts(CRMM_ACCOUNT) PCUI application details tab.I need to read the selected value of first dropdown list item,based on that second dropdown list will be populated.
    I know where to populate the dropdown list box,it is in FILL_DROPDOWN_LISTBOX.
    I dont know how to trap the selection made on dropdown list.
    PLease guide me on how to trap the dropdown list field selection value.
    Thanks in advance.
    Thirumala.

    Hello,
    Check what is done in standard for the fielf REGION which is inked to the country.
    Otherwise, you can do the following :
    - in field group customizing, for field 1, flag the 'send request' flag. So, when you change the value in this field via the dropdown, the MAC methods are immediately called.
    - Put the new value in a global variable (GV).
    - in the fill_dropdown_listbox method, get the value from this GV and based on it, filter the values for the dropdown of field 2.
    Hope this will help you,
    Regards,
    Frederic

  • Report query not returning the field value from external table

    hi
    I have an issue regarding reports. I have a query having 4 fields from external table and remaining from db tables. the report query returns all the fields from the db tables and only 2 fields from external table. but the same query if I tried in plsql developer it returns all the fields values.
    Can anyone please help me in this issue.
    Thanks and Regards
    kk

    Duplicate post?
    value not displaying in report whereas it returns in plsql developer
    value not displaying in report whereas it returns in plsql developer
    Please log a SR if you do not get any reply to your thread instead of creating new one.
    Thanks,
    Hussein

  • Returning the Prompt Value for a Variable

    Hi Experts,
    What I am currently trying to do is to return the values from a prompt so that I can use them in a variable. I have two Queries that are built off of two different Universes out of BEx. I do not have the same dimensions in both queries. I am merging the Universes based on the 'Employee ID' field, but I need to display Amount measures from both queries. Currently, this is functioning if I do not run any filters.
    However, as soon as I put a query filter on a dimension that does not exist within both Universes, I have a problem where Query1 is returning a dataset of maybe 10 records, while Query2 still returns a dataset of 100 records. Obviously this presents a problem when aggregating the Amount measures.
    I have tried a number of different ways to create a relationship between the measures and Employee, but I can't get things specific enough if I don't have the filtered dimension in the report. Suppose that I have Company Code filtered to 1200, I would like to show on the report only the employees from Company Code 1200. This is fine if I drag in the Employee dimension from Query1. However, once I drag in the Amount measure from Query2, the numbers are totalled for the entire 100 Employees, rather than the 10.
    I figure that I should be able to specify my results by leveraging some sort of formula. I'm currently experimenting with:
    =sum([Query2].[Amount] ForEach ([Company Code];[Query1].[Employee]) Where ([Company Code] = [Prompt1]))
    Prompt1:
    =UserResponse([Query1];"Prompt1")
    The problem with this is that the UserResponse does not return an array of values that were selected (otherwise it would say #MULTIVALUE). Instead, it seems to concatenate the selections by the user into one field. Unfortunately I can't use that for anything. Is there a way to capture the actual value from the prompt in an array?
    Alternatively, is there a better way to accomplish what I'm doing?
    Thanks,
    Brian Comeau

    Hi Brian
    I'm not familiar with Bex queries but have you tried adding using the query with the filter to be the driver for the values of the second query, so in effect you have 3 queriues:
    Query 1 with filter
    Query 2 with sub-query based on filtered query 1
    Regards
    Charles

  • V$session prev_hash_value not returning the correct value?

    Hello,
    I am executing a plsql package (which has the following query) in two modes: through Toad and through a deployed web application. I get two results.
    SELECT sa.sql_text,
    sa.sql_id,
    ss.sid
    FROM v$session ss,
    v$sqlarea sa
    WHERE ss.status = 'ACTIVE'
    AND sa.hash_value = ss.prev_hash_value
    AND ss.username = USER;
    Toad gives me the correct result. The query above pulls the correct SQL statement. But when running through the web application it gives me
    some random SQL statement executed during that session. I thought it might have something to do with pooled JDBC connections so I made sure for that
    execution I created a new dedicated JDBC connection. Still did not work. I used the function SYS_CONTEXT('USERENV', 'SID') to report the session id
    from my java program and from the query above. Both return the same SID. I've tried different variations of that query above (removing status = ACTIVE, removing username = USER, etc...)
    and I still get the same result.
    So any thoughts on what's going on?
    Thanks,
    Piyush

    I believe I figured it out. My testing was flawed. The testing in Toad was directly calling my package (e.g., pkg_b). The web app doesn't do that. It calls pkg_a which does a bunch of setup and then calls the target package (pkg_b) using EXECUTE IMMEDIATE. Apparently the v$session stops collecting info at that point. The current statement always shows as 'BEGIN :b1 := pkg_b; END;'. But it's still confusing why it would do that. Is there another way to access SQL statements from within that dynamic block?

  • How to display the display value of a select list

    I want to display the display value instead of the return value of a select list but don't know how to do it, can someone help me?

    When you created the select list item, you are ask to provide a list of values query which can either be a SQL query or a Static List, which both follows the pattern of
    Dispaly;Return.
    Example:
    SQL query -
    select 'Yes' col1, 'Y' col2
    from dual
    Static -
    STATIC:Yes;Y
    which will display 'Yes' but will actually, return 'Y'.
    how did you set your select list item?
    Thanks,
    Marilyn

  • How to implement the RemoveLast function in a link list? check my code plz

    Hi guys,
    How to delete the last element in a user defined linklist. I am using the following code to find the last element of the list. It works fine, but i don't know how to remove that element ...
    public Object getRear()
                   rear=front;
                   while (rear !=null)
                        if (rear.getNext()!=null)
                             rear=rear.getNext();
                        else
                             break; //rear Node found
                   if (rear !=null) //list is not empty
                        return rear.getData();
                        return null; //list is empty
         }

    Sorry, I missed out on returning the last element:
    public Object delRear() {
      // I assume front is an instance field pointing to the first element
      if(front != null) {  // list contains something
        Element  rear, pred;  // I assume you have some type like this
        // determine predecessor of last element
        rear = front;
        pred = null;
        while(rear.getNext() != null) {
          pred = rear;
          rear = rear.getNext();
        if(pred == null)  front = null;  // delete only element
        else  pred.setNext(null);  // delete last element
        return  rear; // return deleted element
      else  return  null;

  • How to Refer the Selected value in a Select List

    I have a page item which is a select list. I have a button in my region which when clicked will call a process. This process takes the current value of my page item as a parameter. However, when I select a value from the Select list and click on the button, the page item is still submitting the earlier value, it is not getting updated with the value I selected in the select list. Can someone tell me how I can get the page item value to be updated with the value I selected from the choice list? I tried calling a javascript function from the element attribute of this select list onchange="javascript:setValue(this);") and was trying to set the value of another hidden page item with the value of this select list but then the function is not getting called as well. My function code is something like
    function setValue(pThis)
    for (var i = 0; i < pThis.options.length; i++) {
    if (pThis.options[ i ].selected){
    result= pThis.options;
    html_GetElement('P2_HIDDEN').value = result;
    P2_HIDDEN is my hidden page item

    970829 wrote:
    I have a page item which is a select list. I have a button in my region which when clicked will call a process. This process takes the current value of my page item as a parameter. However, when I select a value from the Select list and click on the button, the page item is still submitting the earlier value, it is not getting updated with the value I selected in the select list.
    How do you know this? Have you used Debug mode to track what is happening when the button is pressed? This will show any changes to item values in session state during page submit and page show processing.
    Can someone tell me how I can get the page item value to be updated with the value I selected from the choice list?
    This should happen automatically with a select list item, if the button is correctly defined to perform a page submit. It will not happen if the button performs a redirect. What action is defined to occur when the button is pressed?
    I tried calling a javascript function from the element attribute of this select list onchange="javascript:setValue(this);") and was trying to set the value of another hidden page item with the value of this select list but then the function is not getting called as well. My function code is something like
    function setValue(pThis)
    for (var i = 0; i < pThis.options.length; i++) {
    if (pThis.options[ i ].selected){
    result= pThis.options;
    html_GetElement('P2_HIDDEN').value = result;
    P2_HIDDEN is my hidden page item
    As detailed above, this should be completely unnecessary, however as an aside, html_GetElement is a very out of date method of accessing an item. What version of APEX are you using? (Always specify which version you're using when you ask a question, to allow us to determine the most appropriate solution to the problem.)

Maybe you are looking for