package linkedlist;
public class DoubleLinkedListDemo {
public static void main(String[] args) {
DNode root = new DNode(1, "南京");
DNode root1 = new DNode(2, "苏州");
DNode root2 = new DNode(3, "无锡");
DNode root3 = new DNode(4, "常州");
DoubleLinkedList dLinkedList = new DoubleLinkedList();
dLinkedList.showList();
System.out.println("=================");
dLinkedList.addNode(root);
dLinkedList.addNode(root1);
dLinkedList.addNode(root2);
//
// dLinkedList.showList();
// System.out.println("=================");
// dLinkedList.deleteNode(root2);
// dLinkedList.showList();
//
// System.out.println("=================");
// dLinkedList.updateNode(root3);
// dLinkedList.showList();
//
System.out.println("=================");
dLinkedList.insertNode(root3, 3);
dLinkedList.showList();
}
}
class DNode {
public DNode prev;
public int data;
public String content;
public DNode(int data, String content) {
super();
this.data = data;
this.content = content;
}
public DNode next;
@Override
public String toString() {
return "DNode [data=" + data + ", content=" + content + "]";
}
}
class DoubleLinkedList {
DNode head = new DNode(0, "");// 头结点
// 添加结点
public void addNode(DNode node) {
DNode temp = head;
while (true) {
if (temp.next == null) {
break;
} else {
temp = temp.next;
}
}
temp.next = node;
node.prev = temp;
}
// 删除结点
public void deleteNode(DNode node) {
if (head.next == null) {
System.out.println("空链表");
return;
}
DNode temp = head.next;
boolean flag = true;
while (flag) {
if (temp.next == null && temp.data == node.data) {
temp.prev.next = null;
flag = false;
} else if (temp.data == node.data && temp.next != null) {
temp.prev.next = temp.next;
temp.next.prev = temp.prev;
flag = false;
}
temp = temp.next;
}
if (flag) {
System.out.println("没有该节点");
} else {
System.out.println("删除成功");
}
}
// 遍历
public void showList() {
if (head.next == null) {
System.out.println("空链表");
return;
}
DNode temp = head.next;
while (temp != null) {
System.out.println(temp);
temp = temp.next;
}
}
// 更新结点
public void updateNode(DNode node) {
if (head.next == null) {
System.out.println("空链表");
return;
}
DNode temp = head.next;
while (temp != null) {
if (temp.data == node.data) {
temp.content = node.content;
}
temp = temp.next;
}
}
// 插入结点后插
public void insertNode(DNode node, int k) {
if (head.next == null || k <= 0) {
System.out.println("无法插入");
return;
}
DNode temp = head.next;
temp.prev = head;
boolean flag = true;
int count = 1;
while (temp != null) {
if (count == k) {
node.next = temp;
node.prev = temp.prev;
temp.prev.next = node;
temp.prev = node;
flag = false;
break;
}
temp = temp.next;
count++;
}
if (!flag && count >= k) {
System.out.println("插入成功");
return;
} else {
System.out.println("无法插入该节点");
return;
}
}
}
双向链表的相关操作
最新推荐文章于 2024-10-19 19:51:37 发布