Running linked_demo_oo.js

➕︎ Aa ➖︎ |Dark 1Dark 2Light|HackFira Code|Back to  PT Mono
// CPCS 324 Algorithms & Data Structures 2
// Demo - linked list
// 2019, Dr. Muhammad Al-Hashimi


// ---------------------------------------------------------
// member property fields and methods define objects whose 
// intercations describe the solution; we still have to give
// a step-by-step description (algorithm) for methods


var a = new List();    // create linked-list object

// any object can be added to list

a.insert(10);                      // insert number
a.insert("bla-bla");               // insert string
a.insert(["ali","saad","saeed"]);  // insert array of strings

// insert object {...} with 3 fields
a.insert( {v_id:5, weight:100, label:"Jeddah"} );

// the method .traverse() returns list contents in an array
document.write("<p>", a.traverse(), "</p>");

// access property field of object stored in index 3
document.write("<p>", a.traverse()[3].label, "</p>");

// document.write() can't print general objects, use
// JSON.stringify() for debugging complex data structures
// replace a.traverse() with your own stuff, try the list a
// replace 'document.write' by 'alert' to display in popup box

document.write("<pre>"+JSON.stringify(a.traverse(), null,"   ")+"</pre>");

console.log(JSON.stringify(a.traverse(), null," "));  // see the programming startup page

// ---------------------------------------------------------
// ! objects pasted below to demo, include linklist.js in
// ! your code; review comments there to learn how it works
// ---------------------------------------------------------

function LNode(item)
{
   this.item = item;
   this.next = null;
}

function List()
{
   this.first = null;
   this.insert = insert;
   this.traverse = traverse;
   this.isEmpty = lEmpty;
}

function lEmpty()
{
   return (this.first == null);
}

function insert(item)
{
   if (this.isEmpty())
      this.first = new LNode(item);
   else
   {
      var l = this.first;
      while (l.next != null)
         l = l.next;
      l.next = new LNode(item);
   }
}

function traverse()
{
   var out = [];
   for (var i=0, l=this.first; l != null; l = l.next )
      out [i++] = l.item;
   return out;
}