双向链表大体与单向链表相同,只不过双向链表的节点中包含一个pre
属性,该属性指向该节点的前一个节点。
双向链表的基本实现
package com.DoubleLinked.study;
public class DoubleLinkedListDemo {
public static void main(String[] args) {
Node n1 = new Node(1, null, null);
Node n2 = new Node(2, null, null);
Node n3 = new Node(3, null, null);
DoubleLinkedList list = new DoubleLinkedList();
list.add(n1);
list.add(n2);
list.add(n3);
list.printList();
// list.delByIndex(0);
// list.printList();
// list.delByIndex(0);
// list.printList();
// System.out.println("查询数据:" + list.selNode(2));
list.updateNode(2, 4);
list.printList();
}
}
/**
* 节点类
*
*/
class Node {
int data;
Node pre;
Node next;
public Node(int data, Node pre, Node next) {
super();
this.data = data;
this.pre = pre;
this.next = next;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
@Override
public String toString() {
return "Node [data=" + data + "]";
}
}
/**
* 链表类
*/
class DoubleLinkedList {
private Node head = new Node(0, null, null);
private Node end = head;
private int length = 0;
/**
* 添加节点
*/
public void add(Node node) {
end.next = node;
node.pre = end;
end = end.next;
length++;
}
/**
* 删除节点(根据index)
*/
public void delByIndex(int index) {
if(index < 0 || index >= length) {
System.out.println("输入数据错误");
return;
}
if(head.next == null) {
System.out.println("链表无数据");
return;
}
Node node = head.next;
while(index > 0) {
node = node.next;
index--;
}
if(node != end) {
node.pre.next = node.next;
node.next.pre = node.pre;
} else {
end = end.pre;
node.pre.next = node.next;
}
length--;
}
/**
* 查找节点
*/
public Node selNode(Integer data) {
if(end == head) {
throw new RuntimeException("链表为空,无法查找");
}
Node node = head.next;
Boolean flag = false;
while(node != null) {
if(node.data == data) {
flag = true;
break;
}
node = node.next;
}
if(flag == false) {
throw new RuntimeException("没有此的数据");
} else {
return node;
}
}
/**
* 修改节点(根据索引修改数据)
*/
public void updateNode(Integer index, Integer data) {
if(length == 0) {
System.out.println("链表为空,无法修改");
return;
}
if(index < 0 || index >= length) {
System.out.println("参数错误!");
return;
}
Node node = head.next;
while(index > 0) {
node = node.next;
index--;
}
node.data = data;
}
/**
* 打印链表
*/
public void printList() {
if(head.next == null) {
System.out.println("链表无数据");
return;
}
Node node = head.next;
StringBuilder sb = new StringBuilder("[ ");
while(node != null) {
sb.append(node.data + ",");
node = node.next;
}
sb.deleteCharAt(sb.length() - 1);
sb.append(" ]");
System.out.println("链表打印:" + sb.toString());
}
}