# 单链表转置

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
1
2
3
4
5
6
7

# 迭代

/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function (head) {
    let p, q;
    p = null
    q = head
    while (q) {
        let k = q.next
        q.next = p
        p = q
        q = k
    }
    return p
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 递归

/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function (head) {
    const fn = (p, q) => {
        if (!q) {
            return p
        }
        let k = fn(q, q.next)
        q.next = p
        return k
    }
    return fn(null, head)
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15