javascript数据结构(四)链表

链表结构示意图

function LinkList() {
	let Node = function(element) {
		this.element = element;
		this.next = null;
	};

	let length = 0,
		head = null;
	this.append = function(element) {
		let node = new Node(element),
			currrent;
		if (head === 0) {
			head = node;
		} else {
			currrent = head;
		
			while(currrent.next){
				currrent = currrent.next;
			}
			currrent.next = node;
		}	
		length++;
	};
	this.insert = function(position, element) {
		if (position > -1 && position < length) {
			let node = new Node(element),
				currrent = head,
				previous,
				index = 0;
			if (position === 0) {
				node.next = currrent;
				head = node;
			} else {
				while(index++ < position) {
					previous = currrent;
					currrent = currrent.next;
				}
				node.next = currrent;
				previous.next = node;
			}
			length++;

			return true;
		} else {
			return false;
		}
	};
	this.removeAt = function(position, element) {
		if (position > -1 && position < length ) {
			let currrent = head,
				previous,
				index = 0;
			if (position === 0) {
				head = currrent.next;
			} else {
				while(index++ < position) {
					previous = currrent;
					currrent = currrent.next;
				}
			 	previous.next = currrent.next;
			}
			length--;
			return currrent.element;
		} else {
			return null;
		}
	};
	this.remove = function(element) {
		// 需要借助index方法和removeAt方法
		let index = this.indexOf(element),
			return this.removeAt(index);
	};
	this.indexOf = function(element) {
		let currrent = head,
			index = -1;
		while(currrent) {
			if (currrent.element === element) {
				return index;
			}
			index++;
			currrent = currrent.next;
		}
		return -1;
	};
	this.isEmpty = function(){
		return length === 0;
	};
	this.size = function(){
		return length;
	};
	this.getHead = function() {
		return head;
	};
//转化为tostring
	this.toString = function() {
		let currrent = head,
			string = '';
		while(currrent.next) {
			string += currrent.element +(currrent.next ? 'n' : '');
			currrent = currrent.next;
		}
		return string;	
	};
//打印
	this.print = function() {
        let current = head;
        while(current.next){
            console.log(current.element);
            current = current.next;
        }
	};
}

猜你喜欢

转载自blog.csdn.net/qq_35532442/article/details/81133706