基于Java代码实现双向链表
package com.test.list;
import java.util.Iterator;
public class DoubleLinkedListDemo<T> implements Iterable {
//头节点
private Node head;
//尾节点
private Node last;
//链表长度
private int L;
//构造方法
public DoubleLinkedListDemo() {
head = new Node(null, null, null);
last = null;
L = 0;
}
//清空链表
public void clear() {
last = null;
head.next = last;
head.pre = null;
head.item = null;
L = 0;
}
//获取链表长度
public int getLength() {
return L;
}
//判断链表是否为空
public boolean isEmpty() {
return L == 0;
}
//添加元素,默认添加到最后
public void insert(T item) {
if (item == null) {
throw new RuntimeException("参数不合法!!!");
}
if (last == null) {
last = new Node(item, head, null);
head.next = last;
} else {
Node oldNode = last;
Node newNode = new Node(item, oldNode, null);
oldNode.next = newNode;
last = newNode;
}
L++;
}
//添加元素到指定位置
public void insert(T item, int i) {
if (item == null) {
throw new RuntimeException("参数不合法!!!");
}
if (i < 0 || i >= L) {
throw new RuntimeException("位置参数不合法!!!");
}
Node n = head;
if (i == L) {
insert(item);
}
for (int j = 0; j < i; j++) {
n = n.next;
}
Node pre = n;
Node current = n.next;
Node newNode = new Node(item, pre, current);
pre.next = newNode;
current.pre = newNode;
L++;
}
//获取指定位置i的元素
public T get(int i){
if(i<0||i>=L){
throw new RuntimeException("位置参数不合法!!!");
}
Node n = head;
for (int j = 0; j < i; j++) {
n = n.next;
}
return n.item;
}
//根据元素的值,获取改位置的下标
public int indexOfValue(T t){
Node n = head;
for (int i = 0; i < L; i++) {
if(n.item.equals(t)){
return i;
}
n = n.next;
}
return -1;
}
//删除元素
public T remove(int i){
if(i<=0||i>=L){
throw new RuntimeException("位置参数不合法!!!");
}
Node n = head;
if(i==1){
Node nextNode = head.next.next;
Node current = head.next;
head.next = nextNode;
nextNode.pre = head;
L--;
return current.item;
}else{
for (int j = 0; j < i; j++) {
n = n.next;
}
Node pre = n;
Node current = n.next;
Node nextNode = pre.next;
pre.next = nextNode;
nextNode.pre = pre;
L--;
return current.item;
}
}
//获取第一个元素
public T getFirst(){
if(isEmpty()){
return null;
}
return head.next.item;
}
//获取最后一个元素
public T getLast(){
if(isEmpty()){
return null;
}
return last.item;
}
//打印链表数据
public void printData(){
Node n = head.next;
for (int i = 0; i < L; i++) {
System.out.print("[" + i + "]=" + n.item + " ");
n = n.next;
}
System.out.println();
}
private class Node {
T item;
Node pre;
Node next;
public Node(T item, Node pre, Node next) {
this.item = item;
this.pre = pre;
this.next = pre;
}
}
@Override
public Iterator iterator() {
return new DLIterator();
}
private class DLIterator implements Iterator{
private Node n = head;
@Override
public boolean hasNext() {
return n.next!=null;
}
@Override
public Object next() {
n = n.next;
return n.item;
}
}
}