学习笔记--实现LinkedList

来源:互联网 发布:蜂王浆 品牌 知乎 编辑:程序博客网 时间:2024/06/16 17:44

ArrayList部分方法

已测试

package cn.Ray.collection;public class Node {Node pre;Object obj;Node next;public Node() {}public Node(Node pre, Object obj, Node next) {super();this.pre = pre;this.obj = obj;this.next = next;}}
public class MyLinkedList /*implements List*/ {Node first;  //获得头结点,之后按照Node的结构可以一直往后找Node last;   //获得当前链表的最后一个节点private int size;public int size(){return size;}public void add(Object obj){Node temp = new Node();if(first==null){        //链表中没有任何结点的情况下temp.previous =null;  //因为是头结点所以Previous为空temp.obj = obj;temp.next = null;     //后面由于暂时没有结点所以也为空first = temp;   //目前第一个和最后一个都是该节点last = temp;}else{//直接往last节点后增加新的节点temp.previous = last;temp.obj = obj;temp.next = null;last.next = temp;last = temp;}size++;}public void add(int index,Object obj){Node temp = node(index);Node newNode = new Node();newNode.obj = obj;if(temp!=null){Node up = temp.previous;up.next = newNode;newNode.previous = up;newNode.next = temp;temp.previous = newNode;size++;}}private void rangeCheck(int index){if(index<0||index>=size){try {throw new Exception();} catch (Exception e) {e.printStackTrace();}}}public Object get(int index){   rangeCheck(index);Node temp = node(index);if(temp!=null){return temp.obj;}return null;}public Node node(int index){   //按索引找到相应节点的方法,实现List接口必须有的Node temp = null;if(first!=null){if (index < (size >> 1)) {   //如果索引号是前半部分的则从头结点开始遍历查找temp = first;for(int i=0;i<index;i++){temp = temp.next;}}else{temp = last;         //如果索引号是后半部分的则从尾结点开始遍历查找            for (int i = size - 1; i > index; i--){            temp = temp.previous;            }}}return temp;}public void remove(int index){Node temp = node(index);if(temp!=null){         //数据结构的知识,不再详述~Node up = temp.previous;Node down = temp.next;up.next = down;down.previous = up;size--;}}public static void main(String[] args) {MyLinkedList list = new MyLinkedList();list.add("aaa");list.add("bbb");list.add("ccc");list.add("ddd");list.add("eee");list.add(4, "11111111111");list.remove(3);for(int i = 0; i < list.size(); i++){System.out.println(list.get(i));}}}



原创粉丝点击