双链表
双向链表也叫双向表,是链表的一种,它由多个结点组成,每个结点都由一个数据域和两个指针域组成,数据域用来存储数据,其中一个指针域用来指向其后继结点,另一个指针域用来指向前驱结点。链表的头结点的数据域不存储数据,指向前驱结点的指针域值为null,指向后继结点的指针域指向第一个真正存储数据的结点。
按照面向对象的思想,我们需要设计一个类,来描述结点这个事物。由于结点是属于链表的,所以我们把结点类作为链表类的一个内部类来实现
节点API
双向链表API设计
package com.peihj;
import java.util.Iterator;
public class TwowayLinkList<T> implements Iterable<T>{
// 定义节点类
private class Node<T>{
private T item;
private Node pre;
private Node next;
public Node(T item,Node pre,Node next){
this.item = item;
this.pre = pre;
this.next = next;
}
}
// 定义首位节点,链表长度
private Node last;
private Node head;
private int N;
// 实例化
public TwowayLinkList(){
head = new Node(null,null,null);
last = null;
N = 0;
}
// 判断链表是否为空
public boolean isEmpty(){
return N == 0;
}
// 清空链表
public void clear(){
last = null;
head.pre = null;
head.next = null;
head.item = null;
N = 0;
}
// 获取链表长度
public int length(){
return N;
}
// 插入元素,默认插入在最后一个位置
public void insert(T t){
if (isEmpty()){
last = new Node(t,last,null);
head.next = last;
}else {
Node oldlast = last;
Node newlast = new Node(t,oldlast,null);
oldlast.next = newlast;
last = newlast;
}
N++;
}
// 在指定位置插入元素
public void insert(int n,T t){
Node pre = head;
for (int i = 0; i < n; i++) {
pre = pre.next;
}
// 当前节点
Node currnode = pre.next;
// 新构建的节点
Node newnode= new Node<T>(t,pre,currnode);
// 双向链表与单向链表不一样,双向链表是前后同时指向
currnode.pre = newnode;
pre.next = newnode;
N++;
}
// 移除指定的元素
public void remove(int n){
Node pre = head;
for (int i = 0; i < n; i++) {
pre = pre.next;
}
Node nextnode = pre.next.next;
pre.next = nextnode;
nextnode.pre = pre;
N--;
}
@Override
public Iterator<T> iterator() {
return new TIterator();
}
private class TIterator implements Iterator{
private Node n = head;
@Override
public boolean hasNext() {
return n.next != null;
}
@Override
public Object next() {
n = n.next;
return n.item;
}
}
}
class Test1 {
public static void main(String[] args) {
TwowayLinkList<String> twowayLinkList = new TwowayLinkList<>();
twowayLinkList.insert("peihj");
twowayLinkList.insert("zhangsan");
twowayLinkList.insert("lisi");
twowayLinkList.insert(1,"sanmao");
twowayLinkList.remove(1);
twowayLinkList.remove(0);
System.out.println(twowayLinkList.isEmpty());
System.out.println(twowayLinkList.length());
for (String s : twowayLinkList) {
System.out.println(s);
}
}
}
参考
黑马程序员