Algorithm

by Yogesh Rathod

HTML

<div id='div1'>

</div>
<div id='div2'>

</div>

JavaScript

//Program for n’th node from the end of a Linked List
var node = {data:0,next:null}

function createLinkList(){
  var head = Object.create(node)
  var current = head;
  head.data = 0;
  for(i=1;i<10;i++){
    var n =  Object.create(node);
    n.data = i;
    current.next = n;
    current = current.next;
  }
return { 
'print':function(){
      var h = head;
      var c = h;
      var str = '';
       while(c.next!=null){
        str+= c.data + '  ';
        c = c.next;
       }
       document.getElementById('div1').innerText = str;
		},
    'fromLast':function(n){
    	var main = head;
      var ref = head;
      var count = 0;
       while(count < n){
        count++;
        if(ref==null){
        	return -1;
        }
        ref = ref.next;
       }
       if(ref!=null){
       while(ref.next!=null){
  	     main = main.next;
	       ref = ref.next;
       }
       }
        document.getElementById('div2').innerText = n + " last from Link List is : " + main.data;
    }
	} 
}

var foo = new createLinkList();
foo.print();
foo.fromLast(3)