数组和链表的区别

来源:互联网 发布:linux 统计文件夹个数 编辑:程序博客网 时间:2024/05/17 19:20

数组结构:

       数组结构在通过索引进行查询数据时效率比较高,而对于数组插入和删除操作,则效率会比较低,在第一个位置进行插入数据,其余数据就需要依次向后移动,而第一个数据进行删除,则需要所有数据全部向前移,这样的话,就会推出第二种结构,链表结构。

简单的链表:为了保证数据插入和删除,不会影响其他数据的移动,保证线性开销,所以就引出了链接。每个表都不会连续进行存储。

     链表是由一系列节点组成的,每个节点都会有一个链点,这就是next链,而next链则会执行下一个node的引用,所以我们在插入或者删除的时候,需要该表链表next链的指向地址即可,每个节点不需要内存进行连续存储,这样会减小删除和插入的线性开销。

链表结构主要分为两种链表,单向链表和双向链表 ,即单向链表只有一个next链,而双向链表会有next链和pre链。



实现ArrayList:(ArrayList其实是对数组的动态扩充)

package com.baoqiang.list;
import java.util.Iterator;
public class MyArrayList<E> implements Iterable<E>{
private static final int DEFAULT_CAPACITY = 10;
private int theSize;
private E[] theItems;
public E set(int index, E newVal){
if(index < 0 || index >= size()){
throw new ArrayIndexOutOfBoundsException();
}
E old = theItems[index];
theItems[index] = newVal;
return old;
}
public E get(int index){
if(index <0 || index >= size()){
throw new ArrayIndexOutOfBoundsException();
}
return theItems[index];
}
public boolean isEmpty(){
return size() == 0;
}
public void trimToSize(){
ensureCapacity(theSize);
}
public void clear(){
theSize = 0;
theItems = (E[]) new Object[DEFAULT_CAPACITY];
}
public void ensureCapacity(int newCapacity){
if(newCapacity < theSize){
return;
}
E[] old = theItems;
theItems = (E[]) new Object[newCapacity];
for(int i=0; i<size(); i++){
theItems[i] = old[i];
}
}
public int size(){
return theSize;
}
public void add(E newVal){
add(size(),newVal);
}
public void add(int index,E newVal){
if(theItems.length == size()){
ensureCapacity(size()*2+1);
}
for(int i=theSize; i>index; i--){
theItems[i] = theItems[i-1];
}
theItems[index] = newVal;
theSize ++;
}
public E remove(int index){
E old = theItems[index];
for(int i=index;i<size();i++){
theItems[index] = theItems[index+1];
}
theSize--;
return old;
}
public Iterator<E> iterator() {
return new Iterator<E>(){
private int current = 0;
public boolean hasNext() {
return current < size();
}
public E next() {
if(!hasNext()){
throw new java.util.NoSuchElementException();
}
return theItems[current++];
}
public void remove() {
MyArrayList.this.remove(--current);
}
};
}
}

0 0
原创粉丝点击