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

2017-12-01  本文已影响21人  SeasonDe

本文基于学习
最近我在换工作,复习一些基础知识,并在面试过程中把遗忘的知识都捡起来。真的是,不经常用的东西都不会记住,忘得好快。囧。

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,这里也有好多这样的题可以学习。


学习是一条漫漫长路,每天不求一大步,进步一点点就是好的。

上一篇下一篇

猜你喜欢

热点阅读