Created
April 2, 2014 07:12
-
-
Save jayhjkwon/9929293 to your computer and use it in GitHub Desktop.
Linked List in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>JS Bin</title> | |
</head> | |
<body> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 자바스크립트로 Linked List 구현하기 | |
console.log('-------------------'); | |
var head = null; // 처음 노드 | |
var tail = null; // 마지막 노드 | |
var Node = function(val){ | |
this.key = val || null; | |
this.next = null; | |
}; | |
// 새로운 노드를 만들고 tail에 할당 | |
var insertNode = function(val) { | |
var node = new Node(val); | |
if (head === null){ | |
head = node; | |
tail = node; | |
}else{ | |
tail.next = node; | |
tail = node; | |
} | |
}; | |
// head를 지우고 그다음 노드를 head로 설정 | |
var removeNode = function() { | |
var tempHead = head.next; | |
delete window.head; | |
head = tempHead; | |
}; | |
var printNodes = function() { | |
var node = head; | |
while(node) { | |
console.log(node.key); | |
node = node.next; | |
} | |
}; | |
// 역순으로 출력, 재귀호출을 이용한다는 점이 핵심 | |
var printNodesReverse = function(node) { | |
if (node.next) { | |
printNodesReverse(node.next); | |
} | |
console.log(node.key); | |
}; | |
insertNode(1); | |
insertNode(2); | |
insertNode(3); | |
// removeNode(); | |
// console.log('head=' + head.key); | |
printNodes(); | |
printNodesReverse(head); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment