Javascript实现单链表简单操作

简述:

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


知识点:

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 pos
		this.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


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值