package NODE.DLNODE;
public class DLNode {
//数据
Object data;
//前驱结点
DLNode prev;
//后驱结点
DLNode next;
public DLNode(Object data, DLNode prev, DLNode next) {
this.data = data;
this.prev = prev;
this.next = next;
}
//头节点指针
static DLNode head;
//尾节点指针
static DLNode last;
//获取长度
public static int getLength(){
int count=0;
for (DLNode n=head; n != null ; n=n.next ) {
count ++;
}
return count;
}
//插入节点
public static void add(Object data, int index) {
DLNode node=new DLNode(data,null,null);
//插入头部
if (index ==0){
node.next=head;
head.prev=null;
head=node;
}
//插入尾部
else if(index == getLength()){
last.next=node; // 将新的节点与原来的尾部节点进行结构上的关联
node.prev=last;
last=node; // node将成为最后一个节点
}
//中间插入
else {
int temp=0;
for (DLNode n=head; n!=null ; n=n.next){
temp++;
if (temp ==index){
node.next=n.next;
n.next=node;
node.prev=n;
break;
}
}
}
}
//删除节点
public static void remove(int index) {
//删除头部
if (index ==0){
head=head.next;
head.prev=null;
}
//尾部删除
else if(index ==getLength()-1){
last=last.prev;
last.next=null;
}
//超出链表长度 从0开始的
else if (index >= getLength()){
throw new IndexOutOfBoundsException("超出链表长度");
}
//删除中间
else {
int temp=0;
for (DLNode n=head; n!=null ; n=n.next){
temp++;
if (temp ==index){
n.next=n.next.next;
n.next.prev=n;
break;
}
}
}
}
public static void main(String[] args) {
DLNode node1 = new DLNode("aaa", null, null);
DLNode node2 = new DLNode("bbb", node1, null);
DLNode node3 = new DLNode("ccc", node2, null);
DLNode node4 = new DLNode("ddd", node3, null);
node3.setNext(node4);
node2.setNext(node3);
node1.setNext(node2);
head = node1;
last = node4;
System.out.print("当前链表:");
for (DLNode n = head; n != null; n = n.next) {
System.out.println(n.data + " ");
}
add("eee", 2);
System.out.print("插入后链表:");
for (DLNode n = head; n != null; n = n.next) {
System.out.println(n.data + " ");
}
remove(2);
System.out.print("删除后链表:");
for (DLNode n = head; n != null; n = n.next) {
System.out.println(n.data + " ");
}
}
public DLNode() {
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public DLNode getPrev() {
return prev;
}
public void setPrev(DLNode prev) {
this.prev = prev;
}
public DLNode getNext() {
return next;
}
public void setNext(DLNode next) {
this.next = next;
}
}