Monday, January 12, 2009

How to create link list with javascript

Dear Friends,
I found data structures as one of the most interesting subjects in the academic i learned. Before some day i was learning object oriented features of javascript. I tried my hand on implementing a Link List algorithm in javascript and here is what i get.

Let's start building a Link List using JavaScript:

  1. Declaring The basic data structures


    function LinkListNode()
    {
    this.Data = 0;
    this.Next = null;
    }
    function List()
    {
    var First = new LinkListNode();
    }


  2. Adding an Insert method


    List.prototype.addNode=function(_node)
    {
    if(this.First == null)
    {
    this.First = _node;
    }
    else
    {
    var temp = this.First;
    while(temp.Next != null)
    temp=temp.Next;
    temp.Next = _node;

    }
    }


  3. Adding Search Method


    List.prototype.search=function(intData)
    {
    var temp = this.First;
    var node = null;
    while(temp !=null)
    {
    if(temp.Data == intData)
    {
    node= temp;
    break;
    }
    else
    temp = temp.Next;
    }
    return node;
    }


  4. Adding Display Method


    List.prototype.show=function()
    {
    var temp = this.First;
    while(temp != null)
    {
    alert(temp.Data);
    temp=temp.Next;
    }
    }


  5. Adding Edit Method


    List.prototype.edit=function(oldValue,newValue)
    {
    var node = this.search(oldValue);
    if(node !=null)
    node.Data =newValue;
    }


  6. Adding Delete Method


    List.prototype.remove=function(value)
    {
    debugger;
    //if first
    if(this.First.Data == value)
    {
    this.First = this.First.Next
    return value;
    }
    //else
    var temp = this.First.Next;
    var prev = this.First.Next;
    while(temp!=null)
    {
    if(temp.Data == value)
    {
    if(prev.Data == temp.Data)
    this.First.Next = temp.Next;
    else
    prev.Next=temp.Next;
    return;
    }
    else
    {
    prev = temp;
    temp = temp.Next;
    }
    }
    }


  7. Let's test the stuff



    //create data structure object
    var _list= new List();
    //add nodes
    var node = new LinkListNode();
    node.Data = 11;
    _list.addNode(node);

    node = new LinkListNode();
    node.Data = 33;
    _list.addNode(node);

    node = new LinkListNode();
    node.Data = 44;
    _list.addNode(node);

    node = new LinkListNode();
    node.Data = 22;
    _list.addNode(node);

    node = new LinkListNode();
    node.Data = 55;
    _list.addNode(node);

    _list.show();
    //test edit
    _list.edit(11,99);
    _list.show();
    //test remove
    _list.remove(22);
    _list.show();


No comments:

Post a Comment

Please add your valuable comments about this post if it helped you. Thanks

Popular Posts