- 题目描述:
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.
Example 2:
Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.
Example 3:
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
解题思路:快慢指针判断是否有环。看了leetcode其他人的解法,改变了原来的链表结构,个人不建议。
- 示例代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode pre = head;
ListNode a = pre.next;
ListNode b = a.next;
if(pre == null || pre.next == null){
return pre;
}
while(a.next != null && b.next != null){
a.next = pre;
pre.next = b.next;
pre.next.next = b;
pre = a;
a = b;
b = a.next;
}
a.next = pre;
pre.next = b;
return pre;
}
}