采用Java实现数据结构中的顺序表
/**
*Apr 15, 2013
*Copyright(c)JackWang
*All rights reserve
*@Author <a href="mailto:wangchengjack@163.com">JackWang</a>
*/
package com.example.list;
/**
* 顺序表的实现
* @author Administrator
*
*/
public class MySeqList {
private Object[] obj; //存储元素,初始长度为10
private int len; //记录顺序表的长度
private final int maxSize = 10;
/**
* 初始化线性表
*/
public MySeqList() {
this.obj = new Object[10];
this.len = 0;
this.clear();
}
/**
* 判断线性表是否为空
* @return 空返回true
*/
public boolean isEmpty(){
if (len == 0) {
return true;
}
return false;
}
/**
* 判断线性表是否已满
* @return 满返回 true
*/
public boolean isFull(){
if (len == maxSize) {
return true;
}
return false;
}
/**
* 返回线性表的长度
* @return 线性表的长度
*/
public int length(){
return len;
}
/**
* 清空线性表
*/
public void clear() {
for (int i = 0; i < obj.length; i++) {
obj[i] = null;
}
}
/**
* 添加元素
* @param i 要添加元素的脚标
* @param o 要添加的元素
*/
public void insert(int i,Object o){
if (i <1) {
throw new RuntimeException("脚标不规范!");
}
if (obj[i-1] != null) {
for(int j = len-1;j>i;j--){
obj[j+1] = obj[j];
}
obj[i] = o;
len++;
return;
}else {
obj[i-1] = o;
len++;
return;
}
}
/**
* 删除元素
* @param i 要删除的元素索引
*/
public void delete(int i){
if (i > len || i <1) {
throw new RuntimeException("脚标不规范!");
}
for(int j = i;j<len-1;j++){
obj[i-1]=obj[i];
}
obj[len-1] = null;
len--;
}
/**
* 修改元素
* @param i 要修改元素的脚标
* @param newObj 要修改的值
*/
public void update(int i,Object newObj){
if (i > len || i <1) {
throw new RuntimeException("脚标不规范!");
}
obj[i-1] = newObj;
}
/**
* 查找元素
* @param o 要查找的元素
* @return 查到元素的索引
*/
public int find(Object o){
for (int i = 0; i < obj.length; i++) {
if(o.equals(obj[i])){
return i+1;
}
}
return -1;
}
/**
* 当前元素的前一个元素的索引
*/
public int previous(int i){
if (i > len || i <1) {
throw new RuntimeException("脚标不规范!");
}
if( i== 1){
return len;
}
return i-1;
}
/**
* 当前元素的后一个元素的索引
*/
public int next(int i){
if (i > len || i <1) {
throw new RuntimeException("脚标不规范!");
}
if( i == len){
return 1;
}
return i+1;
}
/**
* 遍历输出线性表
* @return
*/
public void print(){
for (int i = 0; i < obj.length; i++) {
System.out.println(obj[i]+" ");
}
System.out.println();
}
/**
* 得到特定脚标的元素
* @param i
* @return
*/
public Object get(int i){
if (i > len || i <1) {
throw new RuntimeException("脚标不规范!");
}
return obj[i-1];
}
}