您的位置:首页 > Web前端 > JavaScript

js数组插入指定位置元素,删除指定位置元素,查找指定位置元素算法

2017-02-24 12:43 861 查看
将元素x插入到顺序表L(数组)的第i个数据元素之前

function InsertSeqlist(L, x, i) {
// 将元素x插入到顺序表L的第i个数据元素之前
if(L.length == Maxsize) {
console.log('表已满');
return;
}
if(i < 1 || i > L.length) {
console.log('位置错');
return;
}
for(var j = L.length;j >= i;j--) {
L[j] = L[j - 1]; // 向右移一位
}
//L.length++;
L[i - 1] = x;

return L;
}

var L = [1, 2, 3, 4, 5, 6, 7];
var Maxsize = 10;

console.log(InsertSeqlist(L, 'new1', 5));
console.log(InsertSeqlist(L, 'new2', 7));


删除线性表L中的第i个数据结构

function DeleteSeqList (L, i) {
// 删除线性表L中的第i个数据结构
if(i < 0 || i > L.length) {
console.log('非法位置');
return;
}
delete L[i];
for(var j = i;j < L.length;j++); {
L[j - 1] = L[j];    // 向左移动
}
L.length--;
return L;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐