Javascript实现单链表简单操作

来源:互联网 发布:网件路由器访客网络 编辑:程序博客网 时间:2024/06/06 17:21

简述:

试用传引用方法,实现链表增加,移除,查找操作。


知识点:

javascript的function实现了类的封装


代码:

<!DOCTYPE html><html><head><script type = "text/javascript">var array = new Array(1,2,3,4,5,6);var Node = function(newData){this.next = null;this.data = null;this.Init = function(){this.data = newData;};this.Init();}//definition of List class var List = function(){this.head = null;this.size = 0;this.Init = function(){this.head = null;this.size = 0;}this.Init();this.Insert = function(newData){this.size += 1;var newNode = new Node(newData);if(this.head == null){this.head = newNode;return;}var tempNode = this.head;while(tempNode.next != null)tempNode = tempNode.next;tempNode.next = newNode;};this.GetData = function(pos){if(pos >= this.size || pos < 0)return null;  else{tempNode = this.head;for(i = 0;i < pos;i++)  tempNode = tempNode.next;  return tempNode.data;   }};//remove the element at posthis.Remove = function(pos){if(pos >= this.size || pos < 0)return null;  this.size -= 1;tempNode = this.head;if(pos == 0){this.head = this.head.next;return this.head;}for(i = 0;i < pos - 1;i++){tempNode = tempNode.next;}tempNode.next = tempNode.next.next;return tempNode.next;}this.Print = function(){document.write("elements in list as follows: <br>");tempNode = this.head;while(tempNode != null){document.write(tempNode.data + " ");tempNode = tempNode.next;}document.write("<br>");};};//RUN TEST:var list = new List();var array = new Array(1,2,3,4,5,6);for(i = 0;i < array.length;i++){list.Insert(array[i]);}list.Print();document.write("now remove action: <br>");list.Remove(5);list.Print();document.write("new size after Remove list[5]:  " + list.size);</script></head><body></body></html>



输出:

elements in list as follows:
1 2 3 4 5 6
now remove action:
elements in list as follows:
1 2 3 4 5
new size after Remove list[5]: 5