Linked lists are among the simplest and most common data structures. A Linked List contains 2 parts data and the link(pointer) to the next data element Though coding of linked list is common in languages such as C, PHP. We will see how to implement in Javascript.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
|
<script type="text/javascript">// <![CDATA[ function Node(data) { this.data = data; this.next = 'null'; } var LinkedList = { firstNode: 'null', lastNode: 'null', insert: function(data) { var node = new Node(data); if(this.firstNode=='null' && this.lastNode=='null') { this.firstNode = node; this.lastNode = node; } else { this.lastNode.next = node; this.lastNode = node; } }, remove: function(key) { var current,previous; current = this.firstNode; while(current.data!=key) { if(current.next=='null'){ return 'null'; } else { previous = current; current = current.next; } } if(current==this.firstNode){ current = this.firstNode.next; this.firstNode = current; } else { previous.next = current.next; } document.write(" <b>After Deleting " + key+ " </b> "); }, display: function() { var current; var listdisplay = ''; current = this.firstNode; while(current!='null') { listdisplay += current.data + " -> "; current = current.next; } document.write("Linked List: " + listdisplay); } } LinkedList.insert(7); LinkedList.insert(2); LinkedList.insert(5); LinkedList.display(); LinkedList.remove(2); LinkedList.display(); // ]]></script> |