请帮我用java写一个,判断单向链表是否有循环链表的代码
时间: 2023-05-12 18:03:56 浏览: 59
可以使用快慢指针的方法来判断单向链表是否有循环链表,具体代码如下:
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while (slow != fast) {
if (fast == null || fast.next == null) {
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}
其中,ListNode 是单向链表的节点类,具体实现可以参考以下代码:
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
相关问题
java的单向循环链表
Java的单向循环链表是一种数据结构,它与单向链表类似,但是最后一个节点指向头节点,形成一个环。这种数据结构可以用于需要循环遍历的场景,比如游戏中的角色移动。
下面是Java实现单向循环链表的示例代码:
```
public class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}
}
public class CircularLinkedList {
Node head;
public void add(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
head.next = head;
} else {
Node current = head;
while (current.next != head) {
current = current.next;
}
current.next = newNode;
newNode.next = head;
}
}
public void print() {
if (head == null) {
System.out.println("List is empty");
} else {
Node current = head;
do {
System.out.print(current.data + " ");
current = current.next;
} while (current != head);
System.out.println();
}
}
}
```
用Java写一个链表翻转
在 Java 中,你可以使用以下代码来实现链表翻转:
```
public class LinkedList {
private Node head;
private static class Node {
private int data;
private Node next;
private Node(int data) {
this.data = data;
}
}
public void addToFront(int data) {
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
}
public void reverse() {
Node current = head;
Node previous = null;
Node next = null;
while (current != null) {
next = current.next;
current.next = previous;
previous = current;
current = next;
}
head = previous;
}
public void printList() {
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
}
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.addToFront(1);
list.addToFront(2);
list.addToFront(3);
list.addToFront(4);
list.addToFront(5);
System.out.println("Original list: ");
list.printList();
System.out.println();
list.reverse();
System.out.println("Reversed list: ");
list.printList();
}
}
```
这段代码实现了一个单向链表类,包含了一些基本的方法,比如添加节点、翻转链表、打印链表。
链表翻转的具体实现在 `reverse` 方法中,通过循环不断地将当前节点的 next 指针指向前一个节点,最后将头节点更新为原来的尾节点即可实现链表翻转。
运行上面的代码,你会得到如下输出:
```
Original list:
5 4 3 2 1
Reversed list:
1 2 3 4 5
```
这就是如何使用 Java 实现链表翻转的基本方法。希望