黑马程序员技术交流社区
标题:
自己简单实现LinkedList代码
[打印本页]
作者:
My_Android
时间:
2016-5-26 09:29
标题:
自己简单实现LinkedList代码
/**
* 定义一个,表示一个节点
* @author hasee
*
*/
public class Node {
private Node previous; // 表示上个节点
private Object obj; // 当前节点的值
private Node next; // 表示下个节点
public Node() {
}
public Node(Node previous, Object obj, Node next) {
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;
}
}
复制代码
/**
* 双向链表简单模拟的实现
* @author hasee
*
*/
public class SxtLinkedList {
private Node first; //表示容器头节点
private Node last; //表示容器尾节点
private int size; //容器存储的元素大小
/**
* 添加一个元素对象
* @param obj
*/
public void add(Object obj){
/**
* 如果first为null,代表没有第一个节点。
* 不为空,代表有第一个节点,直接往last节点后增加一个节点
*/
//创建一个节点
Node n = new Node();
if(first == null){
n.setPrevious(null); //容器的头部节点没有上个节点,所以为null
n.setObj(obj);
n.setNext(null); //容器的尾部节点也有下个节点,所以也为null
first = n; // 节点n代表容器的头部
last = n; // 节点n 也代表容器的尾部
}else{
n.setPrevious(last);
n.setObj(obj);
n.setNext(null);
last.setNext(n); //尾部节点的下一个节点为n节点
last = n; // 当前容器的尾部的节点替换为n
}
size++;
}
/**
* 按照索引位置,取出一个对象
* @param index
* @return
*/
public Object get(int index){
rangeCheck(index); //
Node temp = null;
if(first != null){
temp = first;
for(int i=0;i<index;i++){
temp = temp.getNext();
}
}
return temp.getObj();
}
/**
* 索引检测
* @param index
*/
private void rangeCheck(int index) {
if(index < 0 || index >= size){
try {
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public int size(){
return size;
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2