LinkedList实现原理
Posted yilxq
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LinkedList实现原理相关的知识,希望对你有一定的参考价值。
1 package cn.bjext.collection; 2 3 public class Node { 4 Node previous; 5 Object obj; 6 Node next; 7 8 public Node(){} 9 10 public Node(Node previous, Object obj, Node next) { 11 super(); 12 this.previous = previous; 13 this.obj = obj; 14 this.next = next; 15 } 16 17 public Object getPrevious() { 18 return previous; 19 } 20 public void setPrevious(Node previous) { 21 this.previous = previous; 22 } 23 public Object getObj() { 24 return obj; 25 } 26 public void setObj(Object obj) { 27 this.obj = obj; 28 } 29 public Object getNext() { 30 return next; 31 } 32 public void setNext(Node next) { 33 this.next = next; 34 } 35 }
package cn.bjext.collection; public class SxtLinkedList { private Node first; private Node last; private int size; /* * 获得双向链表的长度 */ public int size(){ return size; } /* * 实现添加对象 */ 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 { n.setPrevious(last); n.setObj(obj); n.setNext(null); last.setNext(n); last=n; } 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++; } } //获得对象 public Object get(int index) { Node temp=node(index); return temp.obj; } /* * 删除指定对象的值 */ public void remove(int index){ Node temp=node(index); if(temp!=null) { Node up=new Node(); Node down=new Node(); up=temp.previous; down=temp.next; up.next=down; down.previous=up; size--; } } public Node node(int index){ Node temp=new Node(); 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 static void main(String[] args) { SxtLinkedList list=new SxtLinkedList(); list.add("444"); list.add("5555"); list.add("555"); list.add("woshi"); list.add("liu"); list.add("xue"); System.out.println(list.get(0)); } }
以上是关于LinkedList实现原理的主要内容,如果未能解决你的问题,请参考以下文章