手写LinkList
2016-08-08 13:50
134 查看
package cn.oumashu.collection; public class Node { private Node previous; private Object obj; private Node next; public Node() { super(); } public Node(Node previous, Object obj, Node next) { super(); this.previous = previous; this.obj = obj; this.next = next; } public Node getPrevious() { return previous; } public void setPrevious(Node previous) { this.previous = previous; } public Object getObj() { return obj; } public void setObj(Object obj) { this.obj = obj; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } }
package cn.oumashu.collection; public class MyLinkList { private Node first; private Node last; private int size; public MyLinkList() { super(); } public int size() { return size; } private void rangeCheck(int index) { if(index<0||index>=size) { try { throw new Exception(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public Node node(int index) { Node temp = null; if(first!=null) { temp = first; for(int i=0;i<index;i++) { temp = temp.getNext(); } } return temp; } public void add(Object obj) { Node temp = new Node(); temp.setObj(obj); if(first==null) { temp.setPrevious(null); temp.setNext(null); first = temp; last = temp; }else { temp.setPrevious(last); temp.setNext(null); last.setNext(temp); last = temp; } size++; } public void add(int index, Object obj) { rangeCheck(index); Node temp = node(index); if(temp!=null) { Node newNode = new Node(); newNode.setObj(obj); Node pretemp = new Node(); pretemp = (temp.getPrevious()); newNode.setPrevious(pretemp); newNode.setNext(temp); pretemp.setNext(newNode); temp.setPrevious(newNode); } size++; } public Object get(int index) { rangeCheck(index); Node temp = node(index); if(temp!=null) { return temp.getObj(); } return null; } public void remove(int index) { rangeCheck(index); Node temp = node(index); if(temp!=null) { Node pretemp = temp.getPrevious(); Node nextemp = temp.getNext(); pretemp.setNext(nextemp); nextemp.setPrevious(pretemp); } size--; } public static void main(String[] args) { MyLinkList list = new MyLinkList(); list.add("a"); list.add("b"); System.out.println(list.get(1)); list.add(1, "c"); System.out.println(list.get(1)); list.remove(1); System.out.println(list.get(1)); System.out.println(list.size()); } }
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序