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

本文基于學(xué)習(xí)
最近我在換工作,復(fù)習(xí)一些基礎(chǔ)知識(shí),并在面試過(guò)程中把遺忘的知識(shí)都撿起來(lái)。真的是,不經(jīng)常用的東西都不會(huì)記住,忘得好快。囧。

javascript算法編程思考.jpg

昨天做了兩個(gè)算法題,這是其中一個(gè)。
后來(lái)發(fā)現(xiàn),原來(lái)這些題主要來(lái)自網(wǎng)站https://leetcode.com/,以前我也瀏覽過(guò),不過(guò)基本都很好少看。

題目如下:

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}
 */

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

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

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

  function findLength(n) {
    if (n.next === null) {
      console.log("已拿到總長(zhǎng)度,遍歷結(jié)束");
      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("已遍歷結(jié)束");
        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,這里也有好多這樣的題可以學(xué)習(xí)。


學(xué)習(xí)是一條漫漫長(zhǎng)路,每天不求一大步,進(jìn)步一點(diǎn)點(diǎn)就是好的。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容