[算法編程]Swap node in a linked list

本文基于學習
最近我在換工作,復習一些基礎知識,并在面試過程中把遺忘的知識都撿起來。真的是,不經常用的東西都不會記住,忘得好快。囧。

javascript算法編程思考.jpg

昨天做了兩個算法題,這是其中一個。
后來發現,原來這些題主要來自網站https://leetcode.com/,以前我也瀏覽過,不過基本都很好少看。

題目如下:

Swap node in a linked list

Given a linked list, swap the kth code counted from the beginning with the kth node counted from the end of the linked list.
Note: You may assume 1 <= k <= length of list.
Notice: You are only allowed to modify the linked list node's reference. DO NOT modify the node's value, otherwise your solution will be disqualified.

Example 1:
Input:
1->2->3->4->5->NULL, k = 2
Output:
1->4->3->2->5->NULL

Example 2:
Input:
1->2->3->4->5->6->NULL, k = 4
Output:
1->2->4->3->5->6->NULL

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

# 可以去這些地方檢驗,下面的代碼我驗證成功
# https://leetcode.com/problems/swap-nodes-in-pairs/discuss/

var swap = function(head, k) {
  if (head === null) {
    console.log("無法處理, ListNode是空的");
    return;
  }
  var n = head;
  var length = 1;

  findLength(n);
  console.log(length);

  function findLength(n) {
    if (n.next === null) {
      console.log("已拿到總長度,遍歷結束");
      return;
    }
    length += 1;
    findLength(n.next);
  }

  var index = 1;
  var node1 = null;
  var node2 = null;

  findNode(n);

  function findNode(n) {
    if (index === k) {
      node1 = n
    } else if (index === length - k + 1) {
      node2 = n;
    }
    if (!node1 || !node2) {
      if (n.next === null) {
        console.log("已遍歷結束");
        return;
      }
      index += 1;
      findNode(n.next);
    } else {
      if (node1.val == node2.val) {
        return;
      }
      node1.val = node1.val * node2.val;
      node2.val = node1.val / node2.val;
      node1.val = node1.val / node2.val;
      return;
    }
  }
  return n;
}

后記:
https://github.com/chihungyu1116/leetcode-javascript,這里也有好多這樣的題可以學習。


學習是一條漫漫長路,每天不求一大步,進步一點點就是好的。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。