【算法练习leetcode篇】之链表——206 Reverse

2019-02-14  本文已影响0人  芒果加奶
  1. Reverse Linked List 反转链表

迭代循环


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

 */
const reverseList = head => {
  let cur = head,
    pre = null;
  while (cur) {
    let next = cur.next; //保留cur.next
    cur.next = pre;
    pre = cur;
    cur = next;
  }
  return pre; //反转后的链表
};

递归

详解:每次递归时打破head和head.next的指针连接,同时将head.next.next也就是下一节点的指向head

/**
 * @param {ListNode} head
 * @return {ListNode}
 */
const reverseList = head => {
  if (head === null || head.next === null) return head;
  let newHead = reverseList(head.next); // 将下一节点传到reverseList递归
  head.next.next = head; //head->1->2 1的指针由2指向head
  head.next = null; // head指针指向null,实现1->head反转
  return newHead;
};
上一篇下一篇

猜你喜欢

热点阅读