1. 程式人生 > >206. 反轉連結串列(JavaScript)

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;
  
};