1.数组实现的线性表
package com.endual.job;
public class Alist<T> {
private T[] entry ;
private int length ;
private static final int MAX_SIZE = 20 ;
public Alist() {
this(MAX_SIZE) ;
}
public Alist(int maxSize) {
this.entry = (T[]) new Object[maxSize] ; // 把一个Object的对象数组强制的转换为T[]
this.length = 0 ;
}
public void add (T t) {
if (length <= MAX_SIZE) {
this.entry[length] = t ;
length ++ ;
return ;
}
T[] tempEntry = (T[]) new Object[2*entry.length] ;
for (int i=0; i<entry.length; i++) {
tempEntry[i] = entry[i] ;
}
entry = tempEntry ;
entry[length] = t ;
length ++ ;
}
}
类似这样,优缺点
数组的实现线性的表是很简单的,并且可以直接访问任何的元素,只要知道该元素在数组中的位置就可以了,
而且插入到最后一个也是最简单的,直接添加即可。
但是,由于数组的长度的限制,当超过了数组的长度以后,要动态扩充数组,这样有一个步骤就是要负责数据,这样对于
大数据而言是非常耗费时间的,还有就是插入到数组中某一个位子的时候,要移动大量的数据,也是一个不足,删除也是一样的。这样降低了效率。
2.用链表的形式实现线性表
package job;
public class LinkedAList<T> {
private Node<T> firstNode ;
private int length ;
public LinkedAList() {
firstNode = new Node<T>() ;
}
public void add (T entry) {
if (length == 0) { // 如果是第一个,那么就在第一个上赋值就可以了
firstNode.setData(entry) ;
this.length++ ;
return ;
}
Node<T> nextNode = new Node<T>() ;
nextNode.setData(entry) ;
Node<T> tail = firstNode ;
for (int i=0; i<length-1; i++) {
tail = tail.getNextNode() ; // 求的最后一个Node
}
tail.setNextNode(nextNode) ; // 怎么会空指针呢
length++ ;
}
//获取到某个位置的Node的数据
public T getNodeAt(int pos) {
if (pos<0 || pos>=this.length) {
return null ;
}
Node<T> tempNode = this.firstNode ;
while (pos>0) {
tempNode = tempNode.getNextNode() ;
pos-- ;
}
T t = tempNode.getData() ;
return t ;
}
//从中间插入进去,pos从1的位置开始算起,如果他是1,那么就作为头结点了
public boolean insert(T t, int pos) {
boolean isSuccess = false ;
if (pos<=0 || pos>length) { // 如果超过了这个长度,那么当然是不能插入了的
return isSuccess;
}
Node<T> insertNode = new Node<T>() ; // 要插入的Node
insertNode.setData(t) ;
if (pos==1) {
insertNode.setNextNode(this.firstNode) ;
this.firstNode = insertNode ;
length++ ;
return true ;
}
if (pos==this.length) {
this.add(t) ;
return true ;
}
Node<T> tempNode = this.firstNode ; //第一个结点
while (pos>1) {
tempNode = tempNode.getNextNode() ;
pos-- ;
}
Node<T> nextNode = tempNode.getNextNode() ; // 获取到Pos位置的下一个Node
tempNode.setNextNode(insertNode) ;
insertNode.setNextNode(nextNode) ;
return true ;
}
//获取到当前的链表的长度
public int getLength() {
return this.length ;
}
public String toString() {
int temp = this.length ;
Node<T> tempNode = this.firstNode ;
while (temp>0) {
T t = tempNode.getData() ;
System.out.println(t) ;
tempNode = tempNode.getNextNode() ;
temp-- ;
}
return null ;
}
}
好处当然是插入删除的时候,没有移动数据,而且添加的数据是没有限制的。
不足的地方就是查找的时候,需要时间来查找。