手写LinkedList,彻底理解LinkedList
我们都知道,List下面有两个实现类,ArrayList和LinkedList,但是他们两个实现方式却不一样,
上期我们写了,看到的朋友应该可以理解了,ArrayList底层是利用数组实现的,但是LinkedList是链表哦。
话不多说直接上代码
package com.util.collection; public class SxtLinkedList implements Lists{ // 链表节点 class Node{ Node prveious; // 链接上一个节点 Object data; // 本节点的数据 Node next; // 链接下个节点 public Node() { } public Node(Node prveious, Object data, Node next) { super(); this.prveious = prveious; this.data = data; this.next = next; } } private Node first; // 保存的上个节点 private Node last; // 当前节点 private int size; @Override // 新增 public void add(Object e) { Node n = new Node(); if (first == null) {// 这里初始化节点 n.data =e; n.prveious = null; n.next=null; first = n; last = n; }else { n.prveious =last; // 这里保存了上一个节点的数据 n.data = e; // 保存本节点的数据 n.next = null; // 下个节点为空 last.next = n; last = n; } size++; } @Override // 删除 public boolean remove(Object o) { NodeRem(Traverse(o)); return true; } @Override // 修改 public void add(int index, Object element) { Traverse(index).data=element; } @Override // 查询 public Object get(int index) { indexCheck(index); return Traverse(index).data; } @Override //返回大小 public int size() { return size; } @Override // 集合是否为空 public boolean isEmpty() { return size == 0; } @Override // 根据索引删除 public void remove(int index) { indexCheck(index); NodeRem(index); } @Override // 清空集合 public void clear() { first = null; last = null; first = new Node(); // 保存的上个节点 last = new Node(); // 当前节点 size = 0; } @Override public void set(int index, Object obj) { Node n = new Node(); n.data = obj; n.next = Traverse(index).next; } @Override public int indexOf(Object o) { return Traverse(o); } @Override public Object[] subList(int fromIndex, int toIndex) { return null; } // 索引检查 private void indexCheck(int index) { if(index > size || index < 0) { try { throw new Exception(); } catch (Exception e) { e.printStackTrace(); System.out.println("索引不能大于数组长度切不能小于0"); } } } // 遍历获取元素 public Node Traverse(int index) { Node d = first; indexCheck(index); if (first != null) { for (int i = 0; i < index; i++) { d = d.next; } } return d; } public int Traverse(Object data) { Node d = first; int index = 0; if (data != null) { while (d.data!= data) { ++index; d = d.next; } } return index; } private void NodeRem(int index) { Node n = Traverse(index); Node b = n.prveious; Node a = n.next; a.next =b; b.prveious = a; size--; } public static void main(String[] args) { Lists list = new SxtLinkedList(); list.add("123"); list.add("456"); list.add("789"); list.add("000"); list.add(3,999); System.err.println("节点大小:"+list.size()); System.err.println("节点查询4:"+list.get(3)); } }
默默地温故知新