数据结构-线性表(Javascript实现)

本文介绍了一个使用JavaScript实现的链表数据结构,包括插入、删除、求长度等基本操作,并提供了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用JavaScript实现链表的插入、删除、求长度等方法。


"use strict"
//结点类
var Node = function(){
	this.data = null;
	this.next = null;
}
//链表类
var LinkList = function(){
	var first = new Node();
	//计算链表长度
	var length = function(){
		let p = first.next;
		let count = 0;
		while(p!=null){
			p=p.next;
			count++;
		}
		return count;
	}
	//在从左到右第i个结点后插入结点,0表示在头插入
	var insert = function(node,index){
		if(arguments.length===1){
			this.push(node);
			return;
		}
		let newNode = new Node();
		newNode.data = node;
		let p = first;
		for(let i=0;i<index;i++){
			if(p.next!=null){
				p = p.next;
			}else{
				newNode.next = p.next;
				p.next = newNode;
				return;
			}
		}
		newNode.next = p.next;
		p.next = newNode;
		return;
	}
	//尾插法插入结点
	var push = function(node){
		let newNode = new Node();
		newNode.data = node;
		let p = first;
		while(p.next!=null){
			p = p.next;
		}
		p.next = newNode;
	}
	//删除尾结点
	var pop = function(){
		let p = first,preNode=null;
		while(p.next!=null){
			preNode = p;
			p = p.next;
		}
		preNode.next = null;
		return p.data;
	}
	//头插法插入结点
	var unshift = function(node){
		let newNode = new Node();
		newNode.data = node;
		newNode.next = first.next;
		first.next = newNode;
	}
	//删除头结点
	var shift = function(node){
		let p = first.next;
		first.next = p.next;
		return p.data;
	}
	//从头数删除索引为i的结点,0表示删除第一个结点
	var remove = function(index){
		if(typeof index!=="number"){
			throw Error("the argument of remove must be a number!");
			return;
		}
		if(index < 0){
			throw Error("the input can't be negative number!");
			return;
		}
		let p = first,preNode = null;
		for(let i=0;i<=index;i++){
			if(p.next!==null){
				preNode = p;
				p = p.next;
			}else{
				throw Error("the input is bigger than the length of list!");
				return;
			}
		}
		preNode.next = p.next;
		return p.data;
	}

	//获取链表数组
	var getList = function(){
		let arr = [];
		let p = first;
		let count = 0;
		while(p.next!=null){
			p = p.next;
			//console.log(p);
			arr[count++] = p.data;
			if(count>100){
				alert("死循环了");
				break;
			}
		}
		return arr;
	}

	return {
		length:length,
		insert:insert,
		push:push,
		unshift:unshift,
		shift:shift,
		pop:pop,
		remove:remove,
		getList:getList
	}
}

var list = new LinkList();
list.push(0);
list.push("id");
list.push(2);
list.unshift(-1);
list.insert(-2,0);
console.log(list.getList());

console.log("pop:",list.pop());
console.log("shift:",list.shift());
console.log("remove:",list.remove(0));
console.log("lenght:",list.length());
console.log(list.getList());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值