自己实现LinkedList底层
来源:互联网 发布:酷开下载软件 编辑:程序博客网 时间:2024/05/22 14:56
手动实现简单的LinkedList
LinkedList底层使用循环双链表实现
//手动实现LinkedList,底层使用双向链表,开始的时候是一个空链表,然后慢慢向其中添加元素package com.ahut.linkedlist;import java.util.Collection;public class MyLinkedList { private Node first;// 链表的第一个节点 private Node last;// 链表的最后一个节点 private int size;// 链表元素节点的个数// 1.LinkedList的两种构造方法 public MyLinkedList() { }// 2.往LinkedList中增加数据 public void add(Object obj) { Node n = new Node(); if (first == null) {// 如果链表为空 n.setPrevious(null); n.setObj(obj); n.setNext(null); first = n; last = n; } else {// 如果链表有节点,把节点往last后插 n.setPrevious(last); n.setNext(null); n.setObj(obj); last = n;// n变成新的最后一个节点 } size++; } // 3.获取链表的节点数 public int size() { return size; }// 4.获取第i个位置的节点 public Object get(int index) { checkElementIndex(index); Node node = node(index); if (node != null) {// 找到元素了 return node; } return null;// 没找到 }// 5.删除第i个位置上的节点 public Node remove(int index) { checkElementIndex(index); Node temp = node(index); if (temp != null) {// 找到第i个位置上的节点 Node up = temp.previous; Node down = temp.next; up.next = down; down.previous = up; } size--; return temp; }// 6.在第i个位置上插入新的节点 public void add(int index, Object obj) { checkPositionIndex(index); if (index == size) { add(obj); } else { Node temp = node(index); Node newNode = new Node(); newNode.obj = obj; if (temp != null) {// 找到第i个节点 Node up = temp.previous; up.next = newNode; newNode.previous = up; newNode.next = temp; temp.previous = newNode; size++; } } } // 取得第i个节点的值,不用for循环找,而是一半一半的找 private Node node(int index) { if (index < (size >> 1)) {// index < size/2 Node temp = null; for (int i = 0; i < index; i++) { temp = temp.next; } return temp; } else {// 从后往前找 Node temp = null; for (int i = size - 1; i > index; i--) { temp = temp.previous; } return temp; } }// 检查下标是否越界 public void checkElementIndex(int index) { if (!(index >= 0 && index < size)) { throw new IndexOutOfBoundsException(); } } public void checkPositionIndex(int index) { if (!(index >= 0 && index <= size)) { throw new IndexOutOfBoundsException(); } }}
0 0
- 自己实现LinkedList底层
- LinkedList底层实现
- LinkedList add方法底层实现
- LinkedList基本方法底层实现
- Java8 LinkedList的底层实现
- ArrayList 与 LinkedList 底层实现
- 自己实现LinkedList
- 实现自己的LinkedList
- JAVA--自己实现LinkedList
- 自己实现的LinkedList
- 自己实现RedisCallBack底层
- ArrayList和LinkedList底层实现与理解
- ArrayList和LinkedList底层实现的区别
- ArrayList和LinkedList底层实现的区别
- 集合第二步: 模拟LinkedList底层实现
- ArrayList、LinkedList、HashMap的底层实现
- ArrayList和LinkedList底层实现的区别
- java自己实现的linkedlist
- 多线程
- so 库的动态加载
- java产生随机数的方式
- 多频率外差三维重建精度验证
- C#结合OpenGL绘图之Tao库
- 自己实现LinkedList底层
- KM算法
- MOOC用Python玩转数据笔记 2
- Dockerfile 的详解
- R语言快速入门_函数入门
- 强烈建议使用UTF编码:
- 当看见squash[i][j]这样的形式时,你不知道它是怎样被声明的!
- linux操作学习05:用户信息文件,用户管理(useradd、userdel、groupadd、groupdel、id、usermod),用户权力下放(sudo),用户认证信息控制(chage)
- 数组与链表