¸®½ºÆ®¸¦ ¸¸µé¾î º¸ÀÚ. ¸®½ºÆ® »ç¿ë¹ý1 list = new
LinkedList();
list.add(1); list.add(2); list.add(3); list.add(4); list.add(0,0); list.add(7,1); list.remove(); //remove 0, result = 7, 1, 2, 3, 4 list.print(); console.log('length: ' + String(list.length)); console.log('=================='); console.log('remove(2): '); list.remove(2); //remove 2, result = 7, 1, 3, 4 var v = list.peek(2); console.log("peek(2): " + String(v)); //result 3 list.print(); console.log('length: ' + String(list.length)); »ç¿ë¹ýÀº °£´ÜÇÏ´Ù. add : ³ëµå¸¦ ¸¶Áö¸·¿¡ Ãß°¡ÇÑ´Ù. add(index, value) : À妽º¿¡ value°ªÀ» Ãß°¡ÇÑ´Ù. remove : À妽º 0 ³ëµå¸¦ Á¦°ÅÇÑ´Ù. remove(index): index ³ëµå¸¦ Á¦°ÅÇÑ´Ù. peek: index ³ëµåÀÇ °ªÀ» °¡Á®¿Â´Ù. LinkedList.js var LinkedList = function(){
this.length = 0; this.headNode = new Node(null); } var Node = function(element){ this.data = element; this.next = null; } LinkedList.prototype.add = function(element, position){ var position = position == undefined? this.length: position; var newNode = new Node(element); var preNode = this.headNode; for(i = 0; i<position; i++){ preNode = preNode.next; } newNode.next = preNode == null ? null: preNode.next; preNode.next = newNode; this.length++; } LinkedList.prototype.remove = function(position){ var ret = null; var position = position==undefined?0:position; if(this.isEmpty()){ console.log("list is Empty"); } else if(position < this.length){ var preNode = this.headNode; for(i = 0;i<position;i++){ preNode = preNode.next; } ret = preNode.next.data; preNode.next = preNode.next.next; this.length--; } else{ console.log("index error"); } return ret; } LinkedList.prototype.peek = function(position){ var ret = null; var position = position==undefined?0:position; if(this.isEmpty()){ console.log("list is Empty"); } else if(position<this.length){ var preNode = this.headNode; for(i = 0;i<position;i++){ preNode = preNode.next; } ret = preNode.next.data; } else{ console.log("index error"); } return ret; } LinkedList.prototype.print = function(position){ var str = "linkedList : "; var node = this.headNode.next; while(node != null){ str += node.data; str += " -> "; node = node.next; }; console.log(str); } LinkedList.prototype.isEmpty = function(){ var ret = false; if(!this.length){ ret = true; } return ret; } javascript¿¡¼´Â ÂüÁ¶°¡ ¾øÀ¸¸é µ¥ÀÌÅÍ°¡ »èÁ¦ µÈ´Ù. |