双链表每个节点都有一个指向前一个节点点的“指针”和一个指向后一个节点的"指针",这样就把每个节点联系了起来构成了一个双向链表。
一、java中的LinkedList的使用
LinkedList是双向链表,既然它继承于AbstractSequentialList,就相当于已经实现了“get(int index)这些接口”。
链表的使用还是比较简单的,java中的LinkedList提供了诸多操作链表的函数。
创建链表及链表的基本操作
public class Test {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<String>();
list.add("a"); // 添加元素
list.add("b");
System.out.println(list); // [a, b]
System.out.println(list.contains("a")); // true 是否包含
list.remove("a"); // 删除元素
System.out.println(list.get(0)); // b 根据index获取元素
}
}
二、创建自己的双向链表MyLinkedList
1 创建节点
首先要创建出节点Node,Node类有三个成员变量和构造函数。
public class MyLinkedList<E> {
// 节点
private class Node{
public E e;
public Node prev;
public Node next;
public Node(E e, Node prev, Node next) {
this.e = e;
this.prev = prev;
this.next = next;
}
public Node(E e) {
this.e = e;
this.prev = null;
this.next = null;
}
public Node() {
this.e = null;
this.prev = null;
this.next = null;
}
}
}
2 链表的初始化
有了节点Node,现在就去构建出链表吧,链表的初始化有MyLinkedList的构造函数完成,初始化成一个头尾相连的双向链表。
public class MyLinkedList<E> {
// 节点
private class Node{
...
}
private Node head;
private Node tail;
private int size;
public MyLinkedList() {
head = new Node();
tail = new Node();
head.next = tail;
tail.prev = head;
size = 0;
}
}
3 任意位置插入元素
public class MyLinkedList<E> {
// 节点
private class Node{
...
}
private Node head;
private Node tail;
private int size;
public MyLinkedList() {
head = new Node();
tail = new Node();
head.next = tail;
tail.prev = head;
size = 0;
}
// 在指定位置上添加元素
public void add(int index, E e) {
Node node = new Node(e);
Node cur = head;
for(int i = 0; i < index; i++) {
cur = cur.next;
}
node.next = cur.next;
cur.next.prev = node;
cur.next = node;
node.prev = cur;
size ++;
}
}
4 根据index获取元素
先判断一下要获取元素的index在前半段还是后半段,再决定是从head或tail开始遍历。
public class MyLinkedList<E> {
// 节点
private class Node{
...
}
private Node head;
private Node tail;
private int size;
public MyLinkedList() {
...
}
// 在指定位置上添加元素
public void add(int index, E e) {
...
}
// 根据index获取元素
public E get(int index) {
Node curPrev = head.next;
Node curTail = tail;
if(index < size / 2) {
for(int i = 0; i < index; i ++) {
curPrev = curPrev.next;
}
return curPrev.e;
}else {
for(int i = size; i > index; i --) {
curTail = curTail.prev;
}
return curTail.e;
}
}
public int getSize() {
return size;
}
}
测试
从尾部添加元素,然后依次次取出
public class Test {
public static void main(String[] args) {
MyLinkedList<String> list = new MyLinkedList<String>();
list.add(list.getSize(),"a");
list.add(list.getSize(),"b");
list.add(list.getSize(),"c");
list.add(list.getSize(),"d");
for (int i = 0; i < list.getSize(); i++) {
System.out.println(list.get(i));
}
}
}
打印结果为:a b c d
改进:
在MyLinkedList中可以构建出很多好用的方法,比如在头部或尾部添加元素,判断是否包含等等。