Java实现单链表,反转链表,检测是否成环
发布人:shili8
发布时间:2025-01-05 07:52
阅读次数:0
**Java 实现单链表**
### 链表定义
javapublic class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
### 链表类
javapublic class LinkedList {
private Node head;
public void addNode(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
}
}
public void printList() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
}
### 反转链表
javapublic class LinkedList {
// ...
public void reverseList() {
Node prev = null;
Node current = head;
while (current != null) {
Node nextNode = current.next;
current.next = prev;
prev = current;
current = nextNode;
}
head = prev;
}
public void printReverseList() {
reverseList();
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
// 回复链表 reverseList();
}
}
### 检测是否成环
javapublic class LinkedList {
// ...
public boolean hasCycle() {
Node slow = head;
Node fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
return true;
}
}
return false;
}
public void printCycle() {
if (!hasCycle()) {
System.out.println("No cycle found.");
return;
}
Node slow = head;
Node fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
break;
}
}
System.out.println("Cycle detected at node " + slow.data);
}
}
### 示例代码
javapublic class Main {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.addNode(1);
list.addNode(2);
list.addNode(3);
list.addNode(4);
list.addNode(5);
System.out.println("Original List:");
list.printList();
System.out.println("Reversed List:");
list.reverseList();
list.printList();
System.out.println("Has Cycle: " + list.hasCycle());
System.out.println("Print Cycle:");
list.printCycle();
}
}
###代码注释* `Node`类定义了链表中的一个节点,包含数据和指向下一个节点的引用。
* `LinkedList`类定义了链表本身,提供添加、打印和反转链表的方法。
* `reverseList()`方法通过将每个节点的next指针指向前一个节点来实现链表的反转。
* `hasCycle()`方法使用快慢指针法检测链表是否成环。
* `printReverseList()`方法先反转链表,然后打印反转后的链表,最后回复链表。
* `printCycle()`方法如果链表有环,则打印环的起始节点。
以上是Java实现单链表、反转链表和检测是否成环的代码示例。

