抽象类实现线性表增删等操作:
public class Sample {
public static void main(String[] args) {
Node n =new Node(10);
System.out.println(n);
}
}
//定义一个线性表list类,声明了所有操作
abstract class List{
//在指定角标index处添加元素e
public abstract void add(int index ,int e) throws IllegalAccessException;
//删除指定角标index处的元素,并返回元素的值
public abstract int delete(int index) throws IllegalAccessException;
//返回指定角标index处的元素
public abstract int get(int index) throws IllegalAccessException;
//修改指定角标处的index元素为新元素e,并返回原先的值
public abstract int set(int index , int e) throws IllegalAccessException;
//返回对象的字符串表现形式,可以不用定义为抽象函数,有共同的类object
public abstract String toString ();
//返回线性表有效元素的个数
public abstract int size();
//清空线性表
public abstract void clear();
//判断线性表是否为空
public abstract boolean isEmpty();
}
class Node {
int data;//数据域
Node next;//指针域
public Node() {
}
public Node(int data) {
this.data = data;
}
public Node(int data, Node next) {
this.data = data;
this.next = next;
}
public String toString() {
return "(" + data + ")";
}
//linkedList
class linkedList extends List {
private Node head;
private int size;
public linkedList() {
head = new Node();
size = 0;
}
public void add(int index, int e) throws IllegalAccessException {
if(index < 0 ||index > size){
throw new IllegalAccessException("get() index out of range");
}
Node pre = getNode(index -1 );
Node n = new Node(e);
n.next = pre.next;
pre.next = n;
size++;
}
//删除指定角标index处的元素,并返回元素的值
public int delete(int index) throws IllegalAccessException {
if(index < 0 ||index >= size){
throw new IllegalAccessException("get() index out of range");
}
Node pre =getNode(index - 1);
Node p = pre.next;
pre.next = p.next;
p.next = null;
size--;
return p.data;
}
//返回指定角标index处的元素
public int get(int index) throws IllegalAccessException {
if(index < 0 ||index >= size){
throw new IllegalAccessException("get() index out of range");
}
return getNode(index).data;
}
//返回指定角标index处的节点对象
private Node getNode(int index) {
Node p = head;
for (int i = 0; i <= index ; i++) {
p = p.next;
}
return p;
}
//修改指定角标处的index元素为新元素e,并返回原先的值
public int set(int index, int e) throws IllegalAccessException {
if(index < 0 || index >= size){
throw new IllegalAccessException("set() index out of range");
}
Node p = getNode(index);
int ret = p.data;
p.data = e;
return ret;
}
@Override
public String toString() {
return null;
}
//返回线性表有效元素的个数
public int size() {
return size;
}
//清空线性表
public void clear() {
head.next = null;
size = 0;
}
//判断线性表是否为空
public boolean isEmpty() {
return size == 0 && head.next == null;
}
}
}



