简体   繁体   中英

Time Complexity of a Recursion Function

Suppose I'm using the following code to reverse print a linked list:

public void reverse(){
    reverse(head);
}

private void reverse(Node h){
    if(h.next==null){
        System.out.print(h.data+" ");
        return;
    }

    reverse(h.next);
    System.out.print(h.data+" ");   
}

The linkedlist is printed out in the opposite order, but I don't know efficient it is. How would I determine the time complexity of this function? Is there a more effecient way to do this?

You can use recursion tree or just expand T(n).Both are essentially same methods. What you are doing is expanding the recursion function by noting down what it does each time it is called in its stack.

For ex. Each time your function is called, it does some constant time stuff (print data) and then recurses. So, expanding it, you'll get : T(n) = d + T(n-1) {since one recursion is done, so one less to go} = d + d + T(n-2) and it will go on until it fizzes out.So your function will go on upto the length of the list.Hence complexity : O(n) check out this : Time complexity of a recursive algorithm

Calculating time complexity of recursive algorithms in general is hard. However, there are plenty of resources available. I would start at this stackoverflow question Time complexity of a recursive algorithm .

As far of the time complexity of this this function, it is O(n) because you call reverse n times (once per node). There are not any more efficient ways to reverse, or even print a list. The problem itself requires you to at least look at every element in the list, which by definition is an O(n) operation.

Suppose your list has n elements. Each call to reverse(Node) reduces the length of the list by a single element. The efficiency is therefore O(n), which is clearly optimal: you can't reverse a list without considering all the elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM