js數組插入指定位置元素,刪除指定位置元素,查找指定位置元素算法


 將元素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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM