java实现线性表
今天复习数据结构的线性表 ,顺便用java实现(虽然学过c,但是荒废了-->>>),java 和c/c++的区别就是少了指针,但是照样可以实现数据结构,它是用对象的引用代替指针,指针可以参与运算,而引用不可以,所以说引用其实还更安全。
下面就是源代码:
先定义接口:
package com.guobing.list;
public interface List {
public void InitList(int initSize);
public void ListInsert(int i, Object obj) throws Exception;
public void ListDelete(int i) throws Exception;
public void DstroyList();
public int ListLength();
public boolean IsEmpty();
public T getElem(int i) throws Exception;
public void ClearList();
}
实现代码:
package com.guobing.listImpl;
import java.util.Arrays;
import com.guobing.list.List;
public class ListImpl implements List{
/**
* 线性表的基本操作 初始化 插入 删除
*/
Object[] date = null;//保存此队列中内容的数组
int current;//表示当前为第几个元素
static int length;//表示数组大小的指针
static int DefaultSize = 10;
/**
* 初始化线性表
*/
@Override
public void InitList(int initsize) {
if(initsize < 0) {
throw new RuntimeException("数组大小错误:" + initsize);
}else {
this.date = new Object[initsize];//定义了一个 initsize个元素的数组
current = 0;//当前为第零个元素
length = initsize;//数组的大小
}
}
@Override
public void ListDelete(int i) throws Exception{
if(current == 0) {
throw new Exception("当前线性表为空");
}
if(i<0||i>length) {
throw new Exception("输入的数字不合法");
}else {
for(int j= i; j<=current; j++) {
date[j] = date[j+1];
}
current --;
}
}
/**
* 销毁线性表
*/
@Override
public void DstroyList() {
for(int i=0; i
this.date[i] = null;
length = 0;
}
}
/**
* 向线性表中插入数据
*/
@Override
public void ListInsert(int i, Object obj) throws Exception{
if(i <0 ||i > length) {
throw new Exception("你输入的数字超过了线性表的最大长度或不符合规范");
} else if(current >= length) { //当前存储空间已满,增加分配
this.date = new Object[length + DefaultSize];
length = length + DefaultSize;
} else {
for(int j = current-1; j>=i; j--) {
date[j+1] = date[j];
}
this.date[i] = obj;
current ++;
}
}
@Override
public int ListLength() {
return this.current;
}
/**
* 清空线性表
*/
@Override
public void ClearList() {
Arrays.fill(date, null);
current=0;
}
@Override
public boolean IsEmpty() {
return this.current==0;
}
/**
* 得到第i个元素
*/
@SuppressWarnings("unchecked")
@Override
public T getElem(int i) throws Exception{
if(i<0||i>length) {
throw new Exception("您输入的数字不合法");
}else {
return (T) this.date[i];
}
}
public static void main(String [] args) throws Exception {
ListImpl list = new ListImpl();
list.InitList(10);
list.ListInsert(0, 2);
list.ListInsert(1, "a");
list.ListInsert(2, "b");
list.ListInsert(2, "bfd");
Object li = list.getElem(2);
System.out.println("Di:"+ li);
System.out.println("第2个元素是:" + list.getElem(2));
for(int i = 0; i < length; i++) {
System.out.print( i +":" + list.date[i] + " ");
}
list.ListDelete(2);
System.out.println("删除后:");
for(int i = 0; i < length; i++) {
System.out.print(i +":" + list.date[i] + " ");
}
}
}