首页 > 其他 > 详细

简单的链表实现

时间:2017-12-16 12:44:25      阅读:221      评论:0      收藏:0      [点我收藏+]

Java LinkedList底层是基于双向链表来实现的,为了更好的理解其实现原理,自己对简单的链表结构做了Java实现,代码如下
class MyLinkedList

public MyLinkedList() {
    this.size = 0;
    this.last = null;
    this.first = null;
    head = first;
}

public boolean add(E e){
    linkLast(e);
    return true;
}

public void reset(){
    head = first;
}

public boolean hasNext(){
    return head != last.next;
}

public E next(){
    Node<E> temp = head;
    head = temp.next;
    return temp.item;
}

private void linkLast(E e) {
    Node<E> la = last;
    Node<E> newNode = new Node<E>(e, la, null);
    last = newNode;
    if (la == null){
        head = newNode;
        first = newNode;
    } else {
        la.next = newNode;
    }
    size++;
}

class Node<E>{
    E item;
    Node<E> pre;
    Node<E> next;

    public Node(E item, Node<E> pre, Node<E> next) {
        this.item = item;
        this.pre = pre;
        this.next = next;
    }
}

}

简单的链表实现

原文:http://www.cnblogs.com/canmeng-cn/p/8046123.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!