開発環境
- OS X Yosemite - Apple (OS)
- Emacs (Text Editor)
- JavaScript (プログラミング言語)
- SpiderMonkey (JavaScript engine)
Data Structures and Algorithms With Javascript (Michael McMillan(著)、O'Reilly Media)のChapter 6(Linked Lists)、Exercises 4.(No. 4245)を解いてみる。
Exercises 4.(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, readline*/
var Node = function (element) {
this.element = element;
this.next = null;
},
LinkedList = function () {
this.head = new Node('head');
},
grades = new LinkedList(),
grade;
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.next = 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);
}
};
grade = readline();
while (grade !== 'quit') {
grades.insert(grade, 'head');
grade = readline();
}
grades.display();
出力結果(Terminal, shell, SpiderMonkey)
$ jslint sample4.js
sample4.js is OK.
$ js sample4.js
A
B
C
D
E
A
B
quit
B
A
E
D
C
B
A
$
0 コメント:
コメントを投稿