Java语言编写一个循环链表,循环链表不用双指针,而是只使用一个指针,这样怎么实现循环的功能的呢?有没有谁能解决!
如图
代码目录:
类代码:
Node
public class Node {
public int data;
public Node next;
public boolean isTail;
public Node(int data) {
this.data = data;
this.next = null;
this.isTail = false;
}
}
CircularLinkedList
public class CircularLinkedList {
private Node head;
// 在链表末尾插入节点
public void insert(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
newNode.next = head;
newNode.isTail = true;
} else {
Node current = head;
while (!current.isTail) { // 找到尾部节点
current = current.next;
}
current.isTail = false;
current.next = newNode;
newNode.next = head;
newNode.isTail = true;
}
System.out.println("插入节点 " + data + " 成功!");
}
// 遍历循环链表
public void display() {
if (head == null) {
System.out.println("循环链表为空!");
} else {
Node current = head;
do {
System.out.print(current.data + " ");
current = current.next;
} while (current != head);
System.out.println();
}
}
}
Main
public class Main {
public static void main(String[] args) {
CircularLinkedList circularLinkedList = new CircularLinkedList();
circularLinkedList.insert(1);
circularLinkedList.insert(2);
circularLinkedList.insert(3);
circularLinkedList.display();
}
}
不知道你这个问题是否已经解决, 如果还没有解决的话:对于Java线程池,这个流程图比较重要:
可以看我这篇文章: