2015年7月20日月曜日

開発環境

Data Structures and Algorithms With Javascript (Michael McMillan(著)、O'Reilly Media)のChapter 6(Linked Lists)、Exercises 1.(No. 4245)を解いてみる。

Exercises 1.(No. 4245)

JavaScript(Emacs)

/*jslint         browser : true, continue : true,
  devel  : true, indent  : 4,    maxerr   : 50,
  newcap : true, nomen   : true, plusplus : false,
  regexp : true, sloppy  : true, vars     : false,
  white  : true
*/

/*global print */
var Node = function (element) {
        this.element = element;
        this.next = null;
    },
    LinkedList = function () {
        this.head = new Node('head');
    };

LinkedList.prototype.find = function (item) {
    var curr_node = this.head;
    while (curr_node.element !== item) {
        curr_node = curr_node.next;
    }
    return curr_node;
};
LinkedList.prototype.insert = function (new_element, item) {
    var new_node = new Node(new_element),
        current = this.find(item);
    new_node.nex = current.next;
    current.next = new_node;
};
LinkedList.prototype.display = function () {
    var curr_node = this.head;
    while (curr_node.next !== null) {
        print(curr_node.next.element);
        curr_node = curr_node.next;
    }
};
LinkedList.prototype.findPrevious = function (item) {
    var curr_node = this.head;
    while (curr_node !== null && curr_node.next.element !== item) {
        curr_node = curr_node.next;
    }
    return curr_node;
};
LinkedList.prototype.remove = function (item) {
    var prev_node = this.findPrevious(item);
    
    if (prev_node.next !== null) {
        prev_node.next = prev_node.next.next;
    }
};
LinkedList.prototype.advance = function (n, item) {
    var curr_node = this.head,
        temp_node;

    while (curr_node.next !== null && curr_node.next.element !== item) {
        curr_node = curr_node.next;
    }
    while (curr_node.next.next !== null && n !== 0) {
        temp_node = curr_node.next;
        curr_node.next = curr_node.next.next;
        temp_node.next = curr_node.next.next;
        curr_node.next.next = temp_node;
        curr_node = curr_node.next;
        n -= 1;
    }
};

var cities = new LinkedList();
cities.insert('Conway', 'head');
cities.insert('Russellville', 'Conway');
cities.insert('Carlisle', 'Russellville');
cities.insert('Alma', 'Carlisle');
cities.display();
print();
cities.advance(2, 'Russellville');
cities.display();
print();
cities.advance(2, 'Conway');
cities.display();
print();
cities.advance(2, 'Russellville');
cities.display();
print();
cities.advance(10, 'Carlisle');
cities.display();

出力結果(Terminal, shell, SpiderMonkey)

$ jslint sample1.js

sample1.js is OK.
$ js sample1.js
Conway
Russellville
Carlisle
Alma

Conway
Carlisle
Alma
Russellville

Carlisle
Alma
Conway
Russellville

Carlisle
Alma
Conway
Russellville

Alma
Conway
Russellville
Carlisle
$

0 コメント:

コメントを投稿

Comments on Google+: