前言
双向链表也叫双向表,是链表的一种,它由多个结点组成,每个结点都由一个数据域和两个指针域组成,数据域用来存储数据,其中一个指针域用来指向其后继结点,另一个指针域用来指向前驱结点。链表的头结点的数据域不存储数据,指向前驱结点的指针域值为null,指向后继结点的指针域指向第一个真正存储数据的结点。
代码示例
public class App {
public static void main(String[] args) {
BidirectionalLinkedList<String> list = new BidirectionalLinkedList<>();
list.insert("aaa");
list.insert("bbb");
list.insert("ccc");
for (String s : list){
System.out.println(s);
}
System.out.println("-------------------------------------");
list.insert(1, "eee");
for (String s : list){
System.out.println(s);
}
System.out.println("-------------------------------------");
String str = list.get(1);
System.out.println(str);
System.out.println("-------------------------------------");
list.remove(1);
for (String s : list){
System.out.println(s);
}
}
//顺序表
static class BidirectionalLinkedList<T> implements Iterable<T>{
//头结点
Node head;
//尾结点
Node last;
//结点个数
int size;
//定义结点类
private class Node {
//结点数据
T item;
//后继结点
Node next;
Node pre;//前驱结点
public Node(T item, Node next,Node pre) {
this.item = item;
this.next = next;
this.pre = pre;
}
}
public BidirectionalLinkedList() {
this.head = new Node(null, null,null);
last = null;
size = 0;
}
public void insert(T t) {
Node newNode ;
if (isEmpty()){
newNode = new Node(t, null,head);
head.next = newNode;
}else {
newNode = new Node(t, null,last);
last.next = newNode;
}
last = newNode;
size++;
}
//往指定索引位置插入元素
public void insert(int index, T t) {
Node n = head;
//获取指定位置的结点
for (int i = 0; i <= index; i++) {
n = n.next;
}
//新结点的next指向原位置的next结点
Node newNode = new Node(t, n,n.pre);
n.pre.next = newNode;
n.pre = newNode;
size++;
}
public T get(int index) {
Node n = head.next;
//获取指定位置的结点
for (int i = 0; i < index; i++) {
n = n.next;
}
return n.item;
}
public T remove(int index) {
Node n = head.next;
//获取指定位置的结点
for (int i = 0; i < index; i++) {
n = n.next;
}
//获取要移除的结点
Node current = n;
n.pre.next = current.next;
current.next.pre = n;
size--;
return current.item;
}
//清空所有元素
public void clear() {
head.next = null;
head.pre =null;
head.item = null;
last = null;
size = 0;
}
public T getFirst(){
if (isEmpty()){
return null;
}
return head.next.item;
}
public T getLast(){
if (isEmpty()){
return null;
}
return last.item;
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
@Override
public Iterator<T> iterator() {
return new LIterator();
}
private class LIterator implements Iterator{
private Node node;
public LIterator() {
this.node = head;
}
@Override
public boolean hasNext() {
return node.next!=null;
}
@Override
public Object next() {
node = node.next;
return node.item;
}
}
}
}