728x90

1. ๊ทธ๋ฅ ์ฝ๋์์ ๋ฐ๋ผ์ค ๋
/** ์ฐ๊ฒฐ ๋ฆฌ์คํธ์ ๊ฐ์ฅ ๊ธฐ๋ณธ์ธ ๋จ์ผ ์ฐ๊ฒฐ ๋ฆฌ์คํธ(Single Linked List) ๋ฅผ ๋ง๋ค์ด๋ณผ๊ฒ์ */
// ๋
ธ๋ ๊ฐ์ฒด ์์ฑ
var Node = function(data) {
// ๋ฐ์ดํฐ์ ๋ค์ ๋
ธ๋์ ์ฃผ์์ง๋ฅผ ๊ฐ์ง๊ณ ์์ด์ผ ํจ
this.data = data;
this.nextNode = null;
}
// Head ์ง์
var Head = null;
// ์ฒซ๋ฒ์งธ ๋
ธ๋ ๋ง๋ค์
var Node1st = new Node("๊น๋ฉ๋ฉ๐ถ");
// Head์ ์ฒซ๋ฒ์งธ ๋
ธ๋ ์ฐธ์กฐ
head = Node1st;
// ๋๋ฒ์งธ ๋
ธ๋ ๋ง๋ค์
var Node2nd = new Node("์ด๋ฅ๋ฅ๐ฑ")
// ์ฒซ๋ฒ์งธ ๋
ธ๋์ ๋ค์ ๋
ธ๋ ์ฃผ์์ง ๊ฐ์ผ๋ก ๋๋ฒ์งธ ๋
ธ๋๋ฅผ ์ฐธ์กฐ
Node1st.nextNode = Node2nd;
// ์ธ๋ฒ์งธ ๋
ธ๋ ๋ง๋ค์
var Node3rd = new Node("๋ฐ๊ฟ๊ฟ๐ท")
// ๋๋ฒ์งธ ๋
ธ๋์ ๋ค์ ์ฃผ์์ง ๊ฐ์ผ๋ก ์ธ๋ฒ์งธ ๋
ธ๋๋ฅผ ์ฐธ์กฐ
Node2nd.nextNode = Node3rd;
// ๋ค๋ฒ์งธ ๋
ธ๋ ๋ง๋ค์
var Node4th = new Node("์ต๋ผ๋ผ๐ต")
// ๋น์ฐํ ์ธ๋ฒ์งธ ๋
ธ๋ ๋ค์ ์ฃผ์์ง ๊ฐ = ๋ค๋ฒ์งธ ๋
ธ๋ ์ฐธ์กฐํ๋๋ก
Node3rd.nextNode = Node4th;
// ๋ค์ฏ๋ฒ์งธ ๋
ธ๋ ์์ฐจ์์ฐจ
var Node5th = new Node("์ ์งน์งน๐ฃ")
// ๋ค๋
ธ๋ค์ฃผ = ๋ค๋
ธ์ฐธ
Node4th.nextNode = Node5th;
// ํ์ธ ํ๋ฒ ๊ฐ๊ฒ์
var linkedListText = "";
var currentNode = head;
while(currentNode != null){
if(linkedListText != "") {
linkedListText += " | "
}
// ๋
ธ๋ ๋ฐ์ดํฐ
linkedListText += currentNode.data;
// ๋
ธ๋์ ๋ค์ ๋
ธ๋ ์ง์
currentNode = currentNode.nextNode;
}
console.log(linkedListText);
// [Result] ๊น๋ฉ๋ฉ๐ถ | ์ด๋ฅ๋ฅ๐ฑ | ๋ฐ๊ฟ๊ฟ๐ท | ์ต๋ผ๋ผ๐ต | ์ ์งน์งน๐ฃ
2. ํจ์ ๋ง๋ค์ด์ ๋ฐ์ดํฐ ๋ฃ์ด์ฃผ๋ ์์ผ๋ก ํ๋ฉด ?
/**
* ์์๋ ๋ฐ์ดํฐ ๊ฐ์ ์ง์ ํด์ค ๊ฑฐ๊ณ ์..
* ๋ง์ฝ์ ํจ์๋ฅผ ์ด์ฉํด์ ๋ฐ์ดํฐ๋ฅผ add ํ๊ฒ ๋๋ฉด์?
* - ๋ง์ง๋ง ๋
ธ๋ ๊ฐ์ฒด๋ฅผ ํญ์ ์ฐพ์์ค์ผํ๋๋ฐ์ ...
*
* ๋ ์ธ ๊ณ
*/
// HEAD
var head = null;
// ํจ์๋ก ๋ฐ์ดํฐ๋ฅผ ์ถ๊ฐํด๋ณผ๊ฒ์
function Nodeadd(data) {
// ์ฐ์ ๋
ธ๋ ๊ฐ์ฒด ์์ฑ
var node = new Node(data);
// HEAD๊ฐ NULL์ด๋ฉด ์ฐ๊ฒฐ๋ ๋
ธ๋(Node)๊ฐ ์๋ ๋น ์ํ(Empty)์ด๋ฏ๋ก ์์ฑ๋ ๋
ธ๋๋ฅผ ์ฐธ์กฐ
// header ์ง์ ํด์ค๊ฑฐ์์
if (head == null) {
head = node;
} else {
// HEAD๊ฐ ์ฐธ์กฐํ๋ ๋
ธ๋ ๋ถํฐ ์์ํ์ฌ ์ฐ๊ฒฐ๋ ๋ง์ง๋ง ๋
ธ๋๋ฅผ ์ฐพ์ต๋๋ค.
var currentNode = head;
while(currentNode.nextNode != null) {
currentNode = currentNode.nextNode;
}
// ๋ง์ง๋ง ๋
ธ๋์ ๋ค์ ๋
ธ๋์ ์์ฑ๋ ๋
ธ๋๋ฅผ ์ฐธ์กฐ์ํต๋๋ค.
currentNode.nextNode = node;
}
}
Nodeadd("๐ถ๊น๋ฉ๋ฉ๐ถ");
Nodeadd("๐ฑ์ด๋ฅ๋ฅ๐ฑ");
Nodeadd("๐ท๋ฐ๊ฟ๊ฟ๐ท");
Nodeadd("๐ฃ์ ์งน์งน๐ฃ");
// ๋จ์ผ ์ฐ๊ฒฐ ๋ฆฌ์คํธ ์ถ๋ ฅ
var linkedListText = "";
var currentNode = head;
while(currentNode != null) {
if (linkedListText != "") {
linkedListText += " ๐ "
}
linkedListText += currentNode.data;
currentNode = currentNode.nextNode;
}
console.log(linkedListText);
// [Result] ๐ถ๊น๋ฉ๋ฉ๐ถ ๐ ๐ฑ์ด๋ฅ๋ฅ๐ฑ ๐ ๐ท๋ฐ๊ฟ๊ฟ๐ท ๐ ๐ฃ์ ์งน์งน๐ฃ

์ฒซ๋ฒ์งธ ๊ฒฐ๊ณผ ๊ฐ๊ณผ ๋๋ฒ์งธ ๊ฒฐ๊ณผ ๊ฐ ์บก์ณ !
728x90