双向链表也叫双链表,是链表的一种,它的每个数据结点中都有两个指针,分别指向直接后继和直接前驱。所以,从双向链表中的任意一个结点开始,都可以很方便地访问它的前驱结点和后继结点。
节点类
class DNode {
public int id;
public String name;
public DNode next;
public DNode pre;
public DNode(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Node{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
链表类
class DoubleLinkedList {
private DNode head = new DNode(0,null);
public void list(){
if (head.next == null){
System.out.println("链表为空!");
return;
}
DNode temp = head.next;
while (true){
if (temp == null){
break;
}
System.out.println(temp);
temp = temp.next;
}
}
public void add1(DNode newNode){
DNode temp = head;
while (true){
if (temp.next == null){
break;
}
temp = temp.next;
}
temp.next = newNode;
newNode.pre = temp;
}
public void remove(int id){
if (head.next == null){
System.out.println("链表为空!");
return;
}
DNode temp = head.next;
boolean flag = false;
while (true){
if (temp == null){
break;
}
if (temp.id == id){
flag = true;
break;
}
temp = temp.next;
}
if (flag){
temp.pre.next = temp.next;
if (temp.next != null){
temp.next.pre = temp.pre;
}
}else {
System.out.println("没有找到要删除的节点,删除失败!");
}
}
public void update(int id,String name){
if (head.next == null){
System.out.println("链表为空!");
return;
}
DNode temp = head.next;
boolean flag = false;
while (true){
if (temp == null){
break;
}
if (temp.id == id){
flag = true;
break;
}
temp = temp.next;
}
if (flag){
temp.name = name;
}else {
System.out.println("没有找到要修改的节点,修改失败!");
}
}
public DNode show(int id){
if (head.next == null){
System.out.println("链表为空!");
return null;
}
DNode temp = head.next;
boolean flag = false;
while (true){
if (temp == null){
break;
}
if (temp.id == id){
flag = true;
break;
}
temp = temp.next;
}
if (flag){
return temp;
}else {
System.out.println("没有找到要查找的节点,查找失败!");
return null;
}
}
}
测试类
public class DoubleLinkedListTest {
public static void main(String[] args) {
DoubleLinkedList doubleLinkedList = new DoubleLinkedList();
DNode node1 = new DNode(1, "阿兰");
DNode node2 = new DNode(2, "洛国富");
DNode node3 = new DNode(3, "艾克森");
doubleLinkedList.add1(node1);
doubleLinkedList.add1(node2);
doubleLinkedList.add1(node3);
doubleLinkedList.list();
doubleLinkedList.list();
}
}
|