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

昨天做了兩個(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)就是好的。