线性表:是有限个元素的集合,除了首尾元素,每个元素都有唯一的前驱和后继元素
一般实现以下方法:InitList()创建表
ClearList()清除表
ListLength()返回表的长度
isEmpty()判断表是否为空
GetElem()取得某个位置元素
SetElem()设置某个位置元素
InsertElem()在某个位置插入元素
DeleElem()删除某位元素
LocationElem() 获得某位元素在表中的位置
顺序存储结构:一般用数组实现,在一段地址连续存储单元依次存放线性表的数据元素
优点:1.无需为元素之间的逻辑关系而增加额外的存储空间
2.可快速存取表中任一元素(存取快)
缺点:1.线性表长度变化大时,无法确定存储空间容量(数组的存储容量固定,不能动态变更)
2.当要增删任一元素时,元素的后续元素都要往前或往后移动一个位置,开销大(增删麻烦)
因此:适用于元素个数固定或变化不大,读取频繁的场景
链式存储结构:线性表的元素存储在不连续的存储单元中,每个元素同时保存指向下一元素存储位置的地址
优点:1.存储空间可变,随需要动态变化
2.可以快速的插入和删除元素(增删快)
缺点:1.读取元素需要通过依次读取链表的方式来获取(读取麻烦)
因此:适用于元素频繁增删,读取较少的场景
public class Node{ private Object object; private Node next; public Node(Object object,Node nextNode){ object = object; next = nextNode; } public Object getObject() { return object; } public void setObject(Object object) { this.object = object; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } public String toString(){ return this.object.toString(); } } public class LinkList{ private Node headNode; private Node currentNode; private int mSize; public LinkList(){ headNode = currentNode = new Node(null,null); mSize = 0; } public void Index(int index) throws Exception{ if(index > mSize-1 || index < -1){ throw new Exception("参数错误"); } if(index == -1){ return; } currentNode = headNode.getNext(); for(int i = 0;i < index;i++){ currentNode = currentNode.getNext(); } } public Object get(int index) throws Exception{ if(index > mSize-1 || index < -1){ throw new Exception("参数错误"); } Index(index); return currentNode.getObject(); } public void insertNode(int i,Node node)throws Exception{ if(i > mSize || i < 0){ throw new Exception("参数错误"); } Index(i-1); currentNode.setNext(new Node(node,currentNode.getNext())); mSize++; } public void DeleNode(int i,Node node)throws Exception{ if(isEmpty()){ throw new Exception("链表为空,无法删除!"); } if(i > mSize || i < 0){ throw new Exception("参数错误"); } Index(i-1); currentNode.setNext(currentNode.getNext().getNext()); mSize--; } public boolean isEmpty(){ return mSize == 0; } public int size(){ return this.mSize; } }