双向链表实现
双向链表和单链表的比较 1.单向链表,查找的方向只能是一个方向,而双向链表可以向前或者向后查找。 2.单向链表不能自我删除,需要靠辅助节点 ,而双向链表,则可以自我删除,所以单链表删除节点时,总是找到删除节点的前一个节点。双向链表java实现代码
public class DoubleLinkedList {
public static void main(String
[] args
) {
Node node
= new Node(1, "aaa");
Node node1
= new Node(2, "bbb");
Node node2
= new Node(3, "ccc");
LinkedList linkedList
= new LinkedList();
linkedList
.addNode(node
);
linkedList
.addNode(node1
);
linkedList
.addNode(node2
);
linkedList
.showNode();
linkedList
.delNode(node1
);
linkedList
.showNode();
}
}
class LinkedList {
private Node head
= new Node(0, "");
public Node
getHeadNode() {
return head
;
}
public void showNode() {
if (head
.next
== null
) {
System
.out
.println("链表为空");
return;
}
Node temp
= head
.next
;
while (temp
!= null
) {
System
.out
.println(temp
);
temp
= temp
.next
;
}
}
public void addNode(Node node
) {
Node temp
= head
;
while (true) {
if (temp
.next
== null
) {
break;
}
temp
= temp
.next
;
}
temp
.next
= node
;
node
.pre
= temp
;
}
public void updateNode(Node node
) {
if (head
.next
== null
) {
System
.out
.println("链表为空");
}
Node temp
= head
.next
;
boolean flag
= false;
while (true) {
if (temp
== null
) {
break;
}
if (temp
.no
== node
.no
) {
flag
= true;
break;
}
temp
= temp
.next
;
}
if (flag
) {
temp
.name
= node
.name
;
} else {
System
.out
.println("没有找到");
}
}
public void delNode(Node node
) {
if (head
.next
== null
) {
System
.out
.println("没有节点");
}
Node temp
= head
.next
;
boolean flag
= true;
while (true) {
if (temp
== null
) {
break;
}
if (temp
.no
== node
.no
) {
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
.printf("要删除的%d节点不存在", node
.no
);
}
}
}
class Node {
public int no
;
public String name
;
public Node pre
;
public Node next
;
public Node(int no
, String name
) {
this.no
= no
;
this.name
= name
;
}
@Override
public String
toString() {
return "Node{" +
"no=" + no
+
", name='" + name
+ '\'' +
'}';
}
}
转载请注明原文地址:https://tech.qufami.com/read-26220.html