Java-2-List集合详解

List集合详解

总的来说,查询多用ArrayList,增删多用LinkedList

在这里插入图片描述

一、数据结构基础

1.1 数组和链表
数组:一种连续存储线性结构,元素类型相同,大小相等

在这里插入图片描述

优点:存取速度快

缺点:长度需事先定义;插入删除很慢;空间通常有限制;需要大块连续内存块

链表:离散存储线性结构

n个节点离散分配,彼此通过指针相连,每个节点只有一个前驱节点,每个节点只有一个后续节点,首节点没有前驱节点,尾节点没有后续节点。

优点:没有空间限制;插入删除很快

缺点:存取速度慢

在这里插入图片描述

确定一个链表只需要头指针

链表又分:

  • 单向链表–一个节点指向下一个节点
  • 双向链表–一个节点有两个指针域
  • 循环链表–能通过任何一个节点找到其他所有的节点,将两种(双向/单向)链表的最后一个结点指向第一个结点从而实现循环
1.2 Java实现链表

算法:遍历、查找、清空、销毁、求长度、排序、删除节点、插入节点

首先,定义一个类作为节点,包含数据域和指针域

public class Node {
   //数据域
   public int data;
   //指针域,指向下一个节点
   public Node next;
   public Node() {
   }
   public Node(int data) {
     this.data = data;
   }
   public Node(int data, Node next) {
     this.data = data;
     this.next = next;
   }
}
1.2.1 创建链表(增加节点)

向链表中插入数据:找到尾节点进行插入;即使头节点.next为null,不走while循环,也是将头节点与新节点连接。

 public static void addData(int value) {
        //初始化要加入的节点
        Node newNode = new Node(value);
        //临时节点
        Node temp = head;
        // 找到尾节点
        while (temp.next != null) {
            temp = temp.next;
        }
        // 已经包括了头节点.next为null的情况了~
        temp.next = newNode;
    }
1.2.2 遍历链表
public static void traverse(Node head) {
        //临时节点,从首节点开始
        Node temp = head.next;
        while (temp != null) {
            System.out.println(temp.data);
            //继续下一个
            temp = temp.next;
        }
    }
1.2.3 插入节点

插入节点到链表中,首先需判断位置是否合法,找到要插入位置的上一个节点即可

public static void insertNode(Node head, int index, int value) {
        //首先需要判断指定位置是否合法,
        if (index < 1 || index > linkListLength(head) + 1) {
            System.out.println("插入位置不合法。");
            return;
        }
        //临时节点,从头节点开始
        Node temp = head;
        //记录遍历的当前位置
        int currentPos = 0;
        //初始化要插入的节点
        Node insertNode = new Node(value);
        while (temp.next != null) {
            //找到上一个节点的位置了
            if ((index - 1) == currentPos) {
                //temp表示的是上一个节点
                //将原本由上一个节点的指向交由插入的节点来指向
                insertNode.next = temp.next;
                //将上一个节点的指针域指向要插入的节点
                temp.next = insertNode;
                return;
            }
            currentPos++;
            temp = temp.next;
        }
    }
1.2.4 获取链表长度

遍历,每得到一个节点+1即可

public static int  linkListLength(Node head) {
        int length = 0;
        //临时节点,从首节点开始
        Node temp = head.next;
        // 找到尾节点
        while (temp != null) {
            length++;
            temp = temp.next;
        }
        return length;
    }
1.2.5 删除节点

将要删除的节点的上一个节点的指针域改变即可

 public static void deleteNode(Node head, int index) {
        //首先需要判断指定位置是否合法,
        if (index < 1 || index > linkListLength(head) + 1) {
            System.out.println("删除位置不合法。");
            return;
        }
        //临时节点,从头节点开始
        Node temp = head;
        //记录遍历的当前位置
        int currentPos = 0;
        while (temp.next != null) {
            //找到上一个节点的位置了
            if ((index - 1) == currentPos) {
                //temp表示的是上一个节点
                //temp.next表示的是想要删除的节点
                //将想要删除的节点存储一下
                Node deleteNode = temp.next;
                //想要删除节点的下一个节点交由上一个节点来控制
                temp.next = deleteNode.next;
                //Java会回收它,设置不设置为null应该没多大意义了(个人觉得,如果不对请指出哦~)
                deleteNode = null;
                return;
            }
            currentPos++;
            temp = temp.next;
        }
    }
1.2.6 链表排序
public static void sortLinkList(Node head) {
        Node currentNode;
        Node nextNode;
        for (currentNode = head.next; currentNode.next != null; currentNode = currentNode.next) {
            for (nextNode = head.next; nextNode.next != null; nextNode = nextNode.next) {
                if (nextNode.data > nextNode.next.data) {
                    int temp = nextNode.data;
                    nextNode.data = nextNode.next.data;
                    nextNode.next.data = temp;
                }
            }
        }
    }
1.2.7 找到链表倒数第k个节点

设置两个指针p1、p2,让p2比p1快k个节点,同时向后遍历,p2为空时p1即为倒数第k个节点

public static Node findKNode(Node head, int k) {
        if (k < 1 || k > linkListLength(head))
            return null;
        Node p1 = head;
        Node p2 = head;
        // p2比怕p1快k个节点
        for (int i = 0; i < k - 1; i++)
            p2 = p2.next;
        // 只要p2为null,那么p1就是倒数第k个节点了
        while (p2.next != null) {
            p2 = p2.next;
            p1 = p1.next;
        }
        return p1;
    }
1.2.8 删除链表重复数据
public static void deleteDuplecate(Node head) {
        //临时节点,(从首节点开始-->真正有数据的节点)
        Node temp = head.next;
        //当前节点(首节点)的下一个节点
        Node nextNode = temp.next;
        while (temp.next != null) {
            while (nextNode.next != null) {
                if (nextNode.next.data == nextNode.data) {
                    //将下一个节点删除(当前节点指向下下个节点)
                    nextNode.next = nextNode.next.next;
                } else {
                    //继续下一个
                    nextNode = nextNode.next;
                }
            }
            //下一轮比较
            temp = temp.next;
        }
    }
1.2.9 查询链表中间节点

设置两个点,一个每次走1步,一个每次走2步,走2步的遍历完,走1步的就是中间节点

public static Node searchMid(Node head) {
        Node p1 = head;
        Node p2 = head;
        // 一个走一步,一个走两步,直到为null,走一步的到达的就是中间节点
        while (p2 != null && p2.next != null && p2.next.next != null) {
            p1 = p1.next;
            p2 = p2.next.next;
        }
        return p1;
    }
1.2.10 递归从尾到头输出单链表
public  static  void printListReversely(Node head) {
        if (head != null) {
            printListReversely(head.next);
            System.out.println(head.data);
        }
    }
1.2.11 反转链表
public static Node reverseLinkList(Node node) {
        Node prev ;
        if (node == null || node.next == null) {
            prev = node;
        } else {
            Node tmp = reverseLinkList(node.next);
            node.next.next = node;
            node.next = null;
            prev = tmp;
        }
        return prev;
    }

在这里插入图片描述

1.3 栈及其Java实现

栈有两种:

  • 静态栈(数组实现)
  • 动态栈(链表实现)
public class Stack {
    //用链表实现栈,需要设置两个指针:栈顶和栈底
    public Node stackTop;
    public Node stackBottom;
    public Stack(Node stackTop, Node stackBottom) {
        this.stackTop = stackTop;
        this.stackBottom = stackBottom;
    }
    public Stack() {
    }
}
1.3.1 进栈

将原本栈顶指向的节点交由新节点来指向,栈顶指向新加入的节点

public static void pushStack(Stack stack, int value) {
        // 封装数据成节点
        Node newNode = new Node(value);
        // 栈顶本来指向的节点交由新节点来指向
        newNode.next = stack.stackTop;
        // 栈顶指针指向新节点
        stack.stackTop = newNode;
    }
1.3.2 遍历栈

只要栈顶元素的指针不指向栈底,就一直输出遍历结果

public static void traverse(Stack stack) {
        Node stackTop = stack.stackTop;
        while (stackTop != stack.stackBottom) {
            System.out.println(stackTop.data);
            stackTop = stackTop.next;
        }
    }
1.3.3 判断栈是否为空

只要栈顶和栈底为同一指向,该栈即为空

public static void isEmpty(Stack stack) {
        if (stack.stackTop == stack.stackBottom) {
            System.out.println("该栈为空");
        } else {
            System.out.println("该栈不为空");
        }
    }
1.3.4 出栈
  1. 出栈前先判断该栈是否为空
  2. 将栈顶元素的指针指向栈顶元素的下一个节点
public static void popStack(Stack stack) {
        // 栈不为空才能出栈
        if (!isEmpty(stack)) {
            //栈顶元素
            Node top = stack.stackTop;
            // 栈顶指针指向下一个节点
            stack.stackTop = top.next;
            System.out.println("出栈的元素是:" + top.data);
        }
    }
1.3.5 清空栈

栈顶指向栈底就能清空栈

public static void clearStack(Stack stack) {
        stack.stackTop = null;
        stack.stackBottom = stack.stackTop;
    }
1.4 队列及其Java实现

队列分为两种:

  • 静态队列(数组实现)
  • 动态队列(链表实现)

往往实现静态队列,都是做成循环队列

在这里插入图片描述

public class Queue {
    //数组
    public int [] arrays;
    //指向第一个有效的元素
    public int front;
    //指向有效数据的下一个元素(即指向无效的数据)
    public int rear;
}
  • rear并不指向最后一个有效的元素,而是指向第一个无效的元素,这样设计就能分清队头和队尾
  • 由于是循环队列,front和rear值会经常变动,因此需要将二者的值限定在一个范围
  • rear = ( rear + 1 ) % 数组长度
1.4.1初始化队列

此时队列为空,分配了6个长度给数组(实际只能装5个)

public static void main(String[] args) {
        //初始化队列
        Queue queue = new Queue();
        queue.front = 0;
        queue.rear = 0;
        queue.arrays = new int[6];
    }
1.4.2 判断队列是否已满

若rear和front指针相邻,说明已满

public static boolean isFull(Queue queue) {
        if ((queue.rear + 1) % queue.arrays.length == queue.front) {
            System.out.println("此时队列满了!");
            return true;
        } else {
            System.out.println("此时队列没满了!");
            return false;
        }
    }
1.4.3 入队
  1. 判断队列是否已满
  2. 入队的值插入到队尾中(即rear指针的位置)
  3. rear指针向后移动
public static void enQueue(Queue queue,int value) {
        // 不是满的队列才能入队
        if (!isFull(queue)) {
            // 将新的元素插入到队尾中
            queue.arrays[queue.rear] = value;
            // rear节点移动到新的无效元素位置上
            queue.rear = (queue.rear + 1) % queue.arrays.length;
        }
    }
1.4.4 遍历

只要front节点不指向rear节点,就可以一直输出

public static void traverseQueue(Queue queue) {
        // front的位置
        int i = queue.front;
        while (i != queue.rear) {
            System.out.println("queue.arrays[i]);
            //移动front
            i = (i + 1) % queue.arrays.length;
        }
    }
1.4.5 判断队列是否为空

若rear和front指向同一位置,队列为空

public static boolean isEmpty(Queue queue) {
        if (queue.rear  == queue.front) {
            System.out.println("此时队列空的!");
            return true;
        } else {
            System.out.println("此时队列非空!");
            return false;
        }
    }
1.4.6 出队
  1. 判断队列是否为空
  2. 不为空则出队,front指针后移
public static void outQueue(Queue queue) {
        //判断该队列是否为null
        if (!isEmpty(queue)) {
            //不为空才出队
            int value = queue.arrays[queue.front];
            System.out.println("出队的元素是:" + value);
            // front指针往后面移
            queue.front = (queue.front + 1) % queue.arrays.length;
        }
    }

二、ArrayList解析

2.1 属性

在这里插入图片描述

在这里插入图片描述

ArrayList底层就是一个数组,可以扩容,实现“动态”增长

2.2 构造方法

在这里插入图片描述

2.3 Add方法

在这里插入图片描述

2.3.1 add(E e)

步骤:

  1. 检查是否需要扩容(尝试容量加1,看是否有必要),容量不足,扩容至原来的1.5倍,若还不够,直接将容量扩充为minCapacity
  2. 插入元素
public boolean add(E e){
    ensureCapacityInternal(size +1); // Increments modCount!
    elementData[size++] = e;
    return true;
}

接下来看+1是否满足要求:

在这里插入图片描述

随后调用ensureExplicitCapacity()来确定明确的容量:

在这里插入图片描述

grow()实现:

在这里插入图片描述

copyOf()实现:

在这里插入图片描述

2.3.2 add(int index, E element)

步骤:

  1. 检查角标
  2. 空间检查,如果不足就扩容
  3. 插入元素

在这里插入图片描述

不难看出,ArrayList的add方法底层都是araycopy()实现的,该方法由C/C++编写

在这里插入图片描述

2.4 get方法
  1. 检查角标
  2. 返回元素

在这里插入图片描述

// 检查角标
private void rangeCheck(int index){
    if(index >= size)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

// 返回元素
E elementData(int index){
    return (E) elementData[index];
}
2.5 set方法
  1. 检查角标
  2. 替代元素
  3. 返回旧值

在这里插入图片描述

2.6 remove方法
  1. 检查角标
  2. 删除元素
  3. 计算需要移动的个数并移动
  4. 设置为null,让GC回收

在这里插入图片描述

2.7 细节说明
  • ArrayList是基于动态数组实现的,在增删时,需要数组的拷贝

  • ArrayList默认初始化容量为10,每次扩容容量增加原来的一半

  • 删除元素不会减少容量,使用trimToSize()减少容量在这里插入图片描述

  • ArrayList不是线程安全的,可以存放null值。

三、Vector与ArrayList共同点与区别

共同点:

两个类都实现了List接口,都是有序的集合(存储有序),底层是数组,可以按位置索引号取出某个元素,允许元素重复和为null

区别:

最大区别:Vecto是同步的(线程安全),但是有性能损失

再要求非同步的情况下,一般都使用ArrayList来替代Vector

要想让ArrayList实现同步,可使用Collections的方法:List list = Collections.synchronizedList(new ArrayList(…));

另一个区别:ArrayList在底层数组不够用时是在原来的基础上扩展0.5倍,Vector是扩展1倍,消耗更多内存

四、LinkedList解析

在这里插入图片描述

LinkedList底层是双向链表,实现了Deque接口,可以像操作队列和栈一样操作LinkedList

4.1 构造方法
// 方法1
public LinkedList(){

}

// 方法2
public LinkedList(Collection<? extends E> c){
	this();
    addAll(c);
}
4.2 add方法
public boolean add(E e){
    linkLast(e);
    return true;
}

void linkLast(E e){
    final Node<E> l = last;
    final Node<E> newNode = new Node<>(l, e, null);
    last = newNode;
    if(l == newNode)
        first = newNode;
    else
        l.next = newNode;
    size++;
    modCount++;
}
4.3 remove方法

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

4.4 get方法
public E get(int index){
	checkElementIndex(index);
	return node(index).item;
}

在这里插入图片描述

4.5 set方法
public E set(int index,E element){
    checkElementIndex(index);
    Node<E> x = node(index);
    E oldVal = x.item;
    x.item = element;
    return oldVal;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值