递归算法的简单应用

耗尽温柔 提交于 2019-11-28 12:22:49

为了确保递归函数不会导致无限循环,它应具有以下属性:

  • 一个简单的基本案例(basic case)(或一些案例) —— 能够不使用递归来产生答案的终止方案。
  • 一组规则,也称作递推关系(recurrence relation),可将所有其他情况拆分到基本案例。

1、以相反的顺序打印字符串

/**
   输入:["h","e","l","l","o"]
   输出:["o","l","l","e","h"]
 */
public class PrintReverseDemo {

    public static void main(String[] args) {
        printReverse("apple".toCharArray());
    }

    private static void printReverse(char[] str) {
        helper(0, str);
    }

    private static void helper(int index, char[] str) {

        if (null == str || index >= str.length) {
            return;
        }
        helper(index + 1, str);
        System.out.print(str[index]);
    }
}

 

2、两两交换链表中的节点

/**
 * 给定 1->2->3->4, 你应该返回 2->1->4->3.
 */
public class SwapNodeDemo {

    public static void main(String[] args){

        ListNode head = makeListNode();

        System.out.println(head);
        System.out.println(swapPairs2(head));
}


    /**
     * 递归
     * @param head
     * @return
     */
    public static ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        
        ListNode p = head.next;
        head.next = swapPairs(head.next.next);
        p.next = head;
        return p;
    }

    /**
     * 非递归
     * @param head
     * @return
     */
    public static ListNode swapPairs2(ListNode head) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode curr = dummy;
        while (curr.next != null && curr.next.next != null) {
            ListNode first = curr.next;
            ListNode second = curr.next.next;

            // swap two nodes
            first.next = second.next;
            second.next = first;
            curr.next = second;

            // update to next iteration
            curr = curr.next.next;
        }
        return dummy.next;
    }

    public static ListNode makeListNode() {
        ListNode one = new ListNode(1);
        ListNode two = new ListNode(2);
        ListNode three = new ListNode(3);
        ListNode four = new ListNode(4);

        one.next = two;
        two.next = three;
        three.next = four;

        return one;
    }

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!