Thursday, May 27, 2010

Insert pada linked list

<html>
<head>
<title>Insert Linked List</title></head>
<body>
<script>
<!--
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(refference)
{
if (refference > -1 && refference < this._panjang)
{
var NodeTanda = this._kepala,
i=0;
while (i++ < refference)
{
NodeTanda = NodeTanda.next;
}
return NodeTanda.data;
} else
{
return null;
}
},

insert : function(refference,data)
{
var node = {data : data, next:null};
var dummy = "";
if( refference > -1 && refference < this._panjang)
{
var NodeTanda = this._kepala, i=0;
this.tambah("");

//posisi refference
while(i++ < refference)
{
NodeTanda = NodeTanda.next;
}

while(refference++ < this._panjang)
{

dummy = NodeTanda.data;
NodeTanda.data = data;
NodeTanda = NodeTanda.next;
data = dummy;
}

}

this._panjang++;
},

Ukuran : function()
{
return this._panjang;
},

toArray : function()
{
var geser = [],
NodeTanda = this._kepala;
while (NodeTanda)
{
geser.push(NodeTanda.data);
NodeTanda = NodeTanda.next;
}
return geser;
},

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 networking");
list.tambah("");

document.write("Isi LinkedList <br>");
document.write("--------------- <br>");
for (i=0;i<5;i++)
{

document.write(list.Item(i) + "<br>");
}
document.write("----------------<br>");

alert("Isi LinkedList awal = " + list.Item(0));

document.write("--------------- <br>");
document.write("<br>");
document.write("--------------- <br>");
document.write("Isi Link list telah dimasukan <br>");
document.write("--------------- <br>");
list.insert(2,"Rumahku Syurgaku");

for (i=0;i<5;i++)
{
document.write(list.Item(i) + "<br>");
}
document.write("----------------<br>");
//-->
</script>
</body>
</html>

0 komentar:

Post a Comment