简单的链表实现

Posted SheaChen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简单的链表实现相关的知识,希望对你有一定的参考价值。

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;
    }
}

}

以上是关于简单的链表实现的主要内容,如果未能解决你的问题,请参考以下文章

合并两个排序的链表

创建一个非常简单的链表

常见的链表排序(Java版)

在 Dartlang 的链表上实现 Iterable 类?

如何打印一个简单的链表(C++)?

[ 链表OJ题--C语言实现 ] 复制带随机指针的链表(带视频讲解哦)