实验二 线性表-单链表(JavaScript实现)

实验二 线性表-顺序表(JavaScript实现)


实验目的

          巩固线性表的数据结构的存储方法和相关操作,学会针对具体应用,使用线性表的相关知识来解决具体问题。


实验内容

        建立一个由n个学生成绩的顺序表,n的大小由自己确定,每一个学生的成绩信息由自己确定,实现数据的对表进行插入、删除、查找等操作。分别输出结果。

要求:

        用顺序表来实现。


实验步骤

//创建一个数组

var array = new Array("小王 80", "小明 60", "晓红 70");   
var Node = function (newData) {           //创建新的节点
    this.next = null;
    this.data = null;
    this.data = newData;
}

//插入元素

this.Insert = function (newData) {
        this.size += 1;
        var newNode = new Node(newData);
        if (this.head == null) {
            this.head = newNode;
            return;
        }
        var tempNode = this.head;
        while (tempNode.next != null)
            tempNode = tempNode.next;
        tempNode.next = newNode;
    };

//删除元素,按位置查找

this.Remove = function (pos) {
        if (pos >= this.size || pos < 0)
            return null;
        this.size -= 1;
        tempNode = this.head;
        if (pos == 0) {
            this.head = this.head.next;
            return this.head;
        }
        for (i = 0; i < pos - 1; i++) {
            tempNode = tempNode.next;
        }
        tempNode.next = tempNode.next.next;
        return tempNode.next;
    }

//查找元素

this.findElem = function (data) { //在表中寻找元素,返回对应的地址位置(按内容查找)
        var Symbol = false;
        var temp = 0;
        for (var i = 0; i < array.length; i++) {
            if (array[i] == data) {
                Symbol = true;
                temp = i + 1; //元素位置
            }
        }
        if (Symbol) {
            return temp;
        }
    }

//代码测试

var list = new List();  //创建一个新的List
for (i = 0; i < array.length; i++) {   //历遍array中的所有元素
    list.Insert(array[i]);
}
list.Print();
console.log("删除后数据:");
list.Remove(2);
list.Print();
console.log("被删除元素位置为: " + list.size);
console.log("数据'小王 80'在:" + list.findElem("小王 80"));


测试结果



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值