2015年7月23日木曜日

開発環境

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

Exercises 3.(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, kjs*/
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.show = function () {
    var curr_node = this.head;

    if (curr_node.next !== null) {
        print(curr_node.next.element);
    }
};
var cities = new LinkedList();
cities.insert('Conway', 'head');
cities.insert('Russellville', 'Conway');
cities.insert('Carlisle', 'Russellville');
cities.insert('Alma', 'Carlisle');
cities.display();
print();
cities.show();

出力結果(Terminal, shell, SpiderMonkey)

$ jslint sample3.js

sample3.js is OK.
MacBook-Pro:ch6 kamimura$ js sample3.js
Conway
Russellville
Carlisle
Alma

Conway
$

0 コメント:

コメントを投稿