1.斐波那契数列
public int fib(int N) {
if(N <= 1) return N;
int first = 0;
int second = 1;
for(int i = 0;i < N - 1;i++){
int sum = first + second;
first = second;
second = sum;
}
return second;
}
2.单链表反转-迭代法
- 遍历链表,遍历的过程中更新pre,head,先用nex提前保存下一个Node节点,每次执行head.next = pre
- 由于需要返回新的链表头部,所以跳出条件为head.next == null,跳出后将head指向pre,返回head
public ListNode reverseList(ListNode head) {
if(head == null) return null;
ListNode pre = null, nex = null;
while(head.next != null) {
nex = head.next;
head.next = pre;
pre = head;
head = nex;
}
head.next = pre;
return head;
}
2.单链表反转-递归思路
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}