实验二 线性表-顺序表(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"));
测试结果