标签:first 一个 node || 方案 nbsp vat apple sys
为了确保递归函数不会导致无限循环,它应具有以下属性:
基本案例(basic case)(或一些案例) —— 能够不使用递归来产生答案的终止方案。递推关系(recurrence relation),可将所有其他情况拆分到基本案例。/**
输入:["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]);
}
}
/**
* 给定 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;
}
标签:first 一个 node || 方案 nbsp vat apple sys
原文地址:https://www.cnblogs.com/kaleidoscope/p/11407032.html