Leetcode:Linked List Cycle--判断链表是否有环

  • 题目描述:
  • Given a linked list, determine if it has a cycle in it.

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;  
    }
}
上一篇:绿盟科技互联网安全威胁周报2016.35 请关注Firefox浏览器远程代码执行漏洞CVE-2016-9079


下一篇:php浮点数计算比较及取整不准确解决方法