LinkedList是一个底层为链表的类,LinkedList继承AbstractSequentialList,与ArrayList一样实现AbstractList接口。LinkedList类具有 size(数据个数),node:prio (前驱),node:next(后继)三个特殊的属性。
与ArrayList一样,LinkedList有add,remove,get等方法,我们可以直接来使用。下面我们来完成一个简单的LinedList(双向链表),完成add,remove,get方法:
class LinkedList {
class Node {
int data;
Node prio;
Node next;
public Node() {
this.data = -1;
this.next = null;
this.prio = null;
}
public Node(int data) {
this.data = data;
this.next = null;
this.prio = null;
}
}
private Node head = null;
public LinkedList () {
this.head = new Node();
}
/**
* 头插法
*/
public void add(int val) {
Node node = new Node(val);
node.next=this.head.next;
node.prio=this.head;
this.head.next=node;
if (node.next != null){ //第一次插入节点的时候
node.next.prio=node;
}
}
/**
* 删除所有值为val的节点
*/
public void remove(int val){
Node cur =this.head.next;
while (cur.next !=null){
if (cur.data == val){
cur.prio.next=cur.next;
if (cur.next != null) {
cur.next.prio = cur.prio;
}
}
cur=cur.next;
}
}
/**
* 打印函数
*/
public void show(){
Node cur = this.head.next;
while (cur != null){
System.out.print(" "+cur.data);
cur=cur.next;
}
System.out.println();
}
}
public class LinkedListDemo {
public static void main(String[] args) {
LinkedList linkedlist= new LinkedList();
LinkedList .add(10);
LinkedList .add(20);
LinkedList .add(30);
LinkedList .show();
}
}
打印结果:
C:\java\java7\jdk1.7.0_80\bin\java.exe -javaagent:D:\ideaIU-
30 20 10
Process finished with exit code 0
ArrayList和LinkedList在性能上各 有优缺点,都有各自所适用的地方,总的说来可以描述如下:
1.对ArrayList和LinkedList而言,在列表末尾增加一个元素所花的开销都是固定的。对 ArrayList而言,主要是在内部数组中增加一项,指向所添加的元素,偶尔可能会导致对数组重新进行分配;而对LinkedList而言,这个开销是 统一的,分配一个内部Node对象。
2.在ArrayList的 中间插入或删除一个元素意味着这个列表中剩余的元素都会被移动;而在LinkedList的中间插入或删除一个元素的开销是固定的。
3.LinkedList不 支持高效的随机元素访问。
4.ArrayList的空 间浪费主要体现在在list列表的结尾预留一定的容量空间,而LinkedList的空间花费则体现在它的每一个元素都需要消耗相当的空间
实现一个简单的LinkedList的Iterator:
import java.util.Iterator;
/**
* 描述:LinkedList的Iterator的实现
* @Author administrator{GINO ZHANG}
* @Date2018/10/16
*/
public class MyLinkedList implements Iterable{
class Node {
private int data;
private Node next;
public Node(int data, Node next) {
super();
this.data = data;
this.next = next;
}
public Object getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
Node head=null;//头节点(以后的元素通过next得到)
Node tail=null;//尾节点
int size=0;
/**
* 尾插
* @param val
* @return
*/
public boolean add(int val){
Node node=new Node(val,null);
if(head == null){
head=node;
tail=node;
}
tail.setNext(node);
tail=node;
size++;
return false;
}
public int size(){
return size;
}
@Override
public Iterator iterator(){
return new MyIterator();
}
class MyIterator implements Iterator{
private Node node=head;//节点
@Override
public boolean hasNext() {
if(node.getNext()==null) return false;
else return true;
}
@Override
public Object next() {
Object o=node.getNext().getData();
node=node.getNext();
return o;
}
}
}