自己实现LinkedListJAVA103-104
2015-11-09 19:52
656 查看
来源:http://www.bjsxt.com/
1、S02E103_01自己实现LinkedList
1、S02E103_01自己实现LinkedList
package com.test.linkedlist; /** * 用来表示一个节点 */ public class Node { Node previous;//该节点的前一个节点 Object obj;//该节点存放的对象 Node next;//该节点的后一个节点 public Node(){ } 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 com.test.linkedlist; public class MyLinkedList { private Node first; private Node last; private int 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{ //直接往last节点后增加新的节点 n.setPrevious(last); n.setObj(obj); n.setNext(null); last.setNext(n);//之前的last指向下一个节点n(之后的last) last = n;//n为最后一个节点 } size++; } public int size(){ return size; } public Object get(int index){ Node temp = getNode(index); return temp.obj; } //index越界处理 public void rangeCheck(int index){ if(index < 0 || index >= size){ try { throw new Exception(); } catch (Exception e) { e.printStackTrace(); } } } public Node getNode(int index){//获得相应索引的节点 rangeCheck(index); Node temp = null; if(first != null){ temp = first; for (int i = 0; i < index; i++) {//遍历节点 temp = temp.next; } } return temp; } public void remove(int index){ Node temp = getNode(index); if(temp != null){ Node up = temp.previous; Node down = temp.next; up.next = down; down.previous = up; size--; } } public void add(int index,Object obj){ Node temp = getNode(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 static void main(String[] args) { MyLinkedList list = new MyLinkedList(); list.add("aaa"); list.add("bbb"); list.add("ccc"); // list.remove(1); list.add(1, "BBB"); System.out.println(list.get(1)); } }
相关文章推荐
- Caused by: java.net.SocketException: Connection reset
- JavaWeb学习篇——使用通用工厂类解耦MVC框架
- Spring进阶一:Spring开发环境搭建
- Java中日期类型和mysql中日期类型进行整合
- spring 国际化
- 用cxf生成webservice的java客户端代码
- java基础第5天(构造代码块、this关键字、构造函数)
- Java transient关键字使用小记
- Java的HashMap底层实现详解
- JAVA反射机制的学习
- 【Java基础】Integer包装类的缓冲池问题
- java实现多继承
- Java内存回收机制(第四讲)
- JAVA基础复习03
- JAVA基础复习03
- eclipse远程调试hadoop2.6
- JAVA模拟POST请求
- spring
- Java程序设计(四)数据库JDBC入门
- JAVA——算术表达式和方法参数计算