「✍ Q: 反转链表」

176 阅读1分钟

双指指针原地反转

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function(head) {

    let cur = head
    let pre = null
   
    while(cur){
      const temp = cur.next
      cur.next = pre || null
      pre = cur
      cur = temp
    }
    return pre
};

递归

 var reverseList = function(head) {

     if(head === null || head.next === null){
         return head
     }

     const node = reverseList(head.next)
     head.next.next = head
     head.next = null
     return node
 }