<html>
<head>
<title>Linked List</title></head>
<body>
<script language = "JavaScript">
<!--
function LinkedList()
{
this._panjang = 0;
this._kepala = null;
}
LinkedList.prototype =
{
constructor : LinkedList,
tambah : function(data)
{
var node = {data : data, next:null};
var NodeTanda;
if (this._kepala === null)
{
this._kepala = node;
} else
{
NodeTanda = this._kepala;
while (NodeTanda.next)
{
NodeTanda = NodeTanda.next;
}
NodeTanda.next = node;
}
this._panjang++;
},
Item : function(index)
{
if (index > -1 && index < this._panjang)
{
var NodeTanda = this._kepala,
i=0;
while (i++ < index)
{
NodeTanda = NodeTanda.next;
}
return NodeTanda.data;
} else
{
return null;
}
},
Buang : function(index)
{
if( index > -1 && index < this._panjang)
{
var NodeTanda = this._kepala,previous, i=0;
if (index === 0)
{
this._kepala = NodeTanda.next;
} else
{
while(i++ < index)
{
previous = NodeTanda;
NodeTanda = NodeTanda.next;
}
previous.next = NodeTanda.next;
}
this._panjang--;
} else
{
return null;
}
},
insert : function(index,data)
{
var node = {data : data, next:null};
var temp = "";
if( index > -1 && index < this._panjang)
{
var NodeTanda = this._kepala, i=0;
this.tambah("x");
//posisi index
while(i++ < index)
{
NodeTanda = NodeTanda.next;
}
while(index++ < this._panjang)
{
temp = NodeTanda.data;
NodeTanda.data = data;
NodeTanda = NodeTanda.next;
data = temp;
}
}
this._panjang++;
},
Ukuran : function()
{
return this._panjang;
},
toArray : function()
{
var result = [],
NodeTanda = this._kepala;
while (NodeTanda)
{
result.push(NodeTanda.data);
NodeTanda = NodeTanda.next;
}
return result;
},
toString : function()
{
return this.toArray().toSring();
}
}
var list = new LinkedList();
list.tambah("Teknik Informatika");
list.tambah("Teknik Komputer");
list.tambah("Komputer Akutansi");
list.tambah("Computer Nerworking");
document.write("Isi LinkedList <br>");
document.write("--------------- <br>");
for (i=0;i<4;i++)
{
document.write(list.Item(i) + "<br>");
}
document.write("----------------<br>");
alert("Isi LinkedList awal = " + list.Item(0));
alert("Item 1 pada LinkedList dibuang, yaitu = " + list.Item(1));
list.Buang(1);
document.write("<br><br>");
document.write("Isi LinkedList Terakhir <br>");
document.write("--------------- <br>");
for (i=0;i<4;i++)
{
if (list.Item(i) == null)
{
document.write("--");
} else {
document.write(list.Item(i) + "<br>");
}
}
document.write("--------------- <br>");
document.write("<br>");
document.write("--------------- <br>");
document.write("Isi Link list disisipkan lagi <br>");
document.write("--------------- <br>");
list.insert(2,"BAKAMONO");
for (i=0;i<4;i++)
{
document.write(list.Item(i) + "<br>");
}
document.write("----------------<br>");
//-->
</script>
</body>
</html>
Langganan:
Posting Komentar (Atom)
Tidak ada komentar:
Posting Komentar