206. 反转链表(JavaScript)

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?


解法一:迭代

设置两个指针,p 和 q,p指向head.next,q指向head.next.next。

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function(head) {
  if (head === null || head.next === null) {    // 链表为空或只有一个节点时,不用反转
    return head;
  }
  var p = head.next;
  head.next = null;    // 让原本的head变为尾节点
  var temp;    // 临时指针
  while (p !== null) {
    temp = p.next;
    p.next = head;
    head = p;
    p = temp;
  }
  return head;
  
};

解法二:递归

递归的方法就是不断调用自身函数,函数返回的是原链表的尾节点,即新链表的头节点。新链表的尾节点指向null。

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function(head) {
  if (head === null || head.next === null) {
    return head;
  }
  
  var new_head = reverseList(head.next);  // 反转后的头节点
  head.next.next = head;                  // 将反转后的链表的尾节点与当前节点相连
  head.next = null;
  return new_head;
  
};

猜你喜欢

转载自blog.csdn.net/romeo12334/article/details/81434182