算法之链表翻转

526 阅读1分钟

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.单链表反转-递归思路

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public ListNode reverseList(ListNode head) {
        //1.第一个条件是判断递归开始传入的参数是合法性的。第二个条件是递归终止条件?
        if(head == null || head.next == null) return head;
        //2.开始递归 4
        ListNode newHead = reverseList(head.next);
        //3.尾部4->5->null,4的后继next指向5
        head.next.next = head;
        //4.5的next指向null
        head.next = null;
        //5.返回翻转后的链表
        return newHead;
    }