LInkedLIst集合
底层结构
链表结构(数据以节点为单位)
单向链表
双向链表
特点
查询效率较低,增删效率较高
定义一个链表结构来实现添加和获取操作
package work03;
public class DemoLinkedList {
public static void main(String[] args) {
MyLinkedList.add("s");
MyLinkedList.add("ssa");
MyLinkedList.add("sa");
System.out.println(MyLinkedList.size);
System.out.println( MyLinkedList.get(2));
}
}
//工具类
class MyLinkedList{
static int size;//数据长度
private static Node head = null;//先定义头指针指向空
//添加元素方法
public static void add(Object obj) {
//1.如果是第一个元素
if(head==null){
head = new Node(obj,null);//将头指针指向新创建的元素节点
size++;
return;
}else{
Node temp = head;//定义临时变量temp存储地址
while (temp.getNext()!=null){//如果temp不指向空
temp = temp.getNext();//temp指向下一个节点地址
}
temp.setNext(new Node(obj,null));//将temp指向新节点
}
size++;
}
//获得该索引位置出的值
public static Object get(int index) {
//如果索引不符合规则抛出异常
if (index<0||index>size){
throw new IndexOutOfBoundsException("索引越界异常");
}
Node temp = head; //定义temp指向head,临时变量
for (int i = 1; i <=size; i++) {
if(i==index){
return temp.getData();//返回该元素
}
temp =temp.getNext();
}
return null;
}
}
//节点类
class Node{
private Object data ;//存放数据
private Node next;//存放下一个节点地址
public Node(Object data, Node next) {
this.data = data;
this.next = next;
}
public Node() {
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}