单链表的实现

这节我们实现一个单链表,有详细的注释。之前贴出代码好了

/*
	链表数据结构的实现
*/

function LinkedList() {
	var Node = function (element) {
		this.element = element;
		this.next = null;
	}

	var length = 0;    
	var head = null;

	/*向列表尾部追加节点*/
	this.append = function (element) {
		var new_node = new Node(element);
		if(head == null) {
			head = new_node;
		} else {
			//insertNode(head, new_node);   // 使用递归来解决也可以
			var current = head;
			while(current.next != null) {
				current = current.next;
			}
			current.next = new_node;
		}

		length++;
	}

	// /*这里*/
	// function insertNode(root, new_node) {
	// 	if(root.next == null) {
	// 		root.next = new_node;
	// 	} else {
	// 		insertNode(root.next, new_node);
	// 	}
	// }

	/*向列表特定位置插入节点*/
	this.insert = function (position, element) {
		if(position < 0 || position>this.size()-1) {
			throw new Error("Position should be in [0, " + (this.size() -1) + "]");
		}

		var new_node = new Node(element);
		if(position == 0) {
			new_node.next = head;
			head = new_node;
		} else {
			var current = head;
			for(var i=1; i<position; ++i) {
				current = current.next;
			}

			new_node.next = current.next;
			current.next = new_node;
		}
		length++;
	}

	/*移除特定位置的节点*/
	this.removeAt = function (position) {
		if(position < 0 || position>this.size()-1) {
			throw new Error("Position should be in [0, " + (this.size() -1) + "]");
		}

		if(position == 0) {
			head = head.next;
		} else {
			var current = head;
			for(var i=1; i<position; ++i) {
				current = current.next;
			}

			current.next = current.next.next;
		}

		length--;
	}

	/*按值相等移除遇到的第一个节点*/
	this.remove = function (element) {
		var index = this.indexOf(element);
		if(index == -1) {
			return;
		}

		this.removeAt(index);
	}

	/*按值相等返回遇到的第一个节点的位置*/
	this.indexOf = function (element) {
		var current = head;
		var cnt = -1;
		while(current != null) {
			cnt++;
			if(element == current.element) {
				return cnt;
			}
			current = current.next;
		}

		if(current == null) {
			return -1;
		}
	}

	/*判断链表是否为空*/
	this.isEmpty = function () {
		return length == 0;
	}

	/*返回链表的大小*/
	this.size = function () {
		return length;
	}

	/*返回链表的头指针或者称为引用*/
	this.getHead = function () {
		return head;
	}

	/*链表只输出值*/
	this.toString = function () {
		var current = head;
		var arr = [];
		while(current != null) {
			arr.push(current.element);
			current = current.next;
		}

		return arr.join(",");
	}

	/*按顺序打印链表*/
	this.print = function () {
		console.log(this.toString());
	}
}

/* Here is a test function */
function test(arr) {
	var linked_list = new LinkedList();
	for(var i=0; i<arr.length; ++i) {
		linked_list.append(arr[i])
	}

	return linked_list;
}

var arr = [10, 20, 30, 40, 50];
var result = test(arr);



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值