LeetCode——Linked List Cycle

来源:互联网 发布:jdbc连接数据库 编辑:程序博客网 时间:2024/06/06 00:24

LeetCode——Linked List Cycle

#141

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

这一题的目的是判断链表中是否有环。一个思路是利用哈希表。如果遍历过的结点已经存在了哈希表,则说明有环。
先用java先,因为java中有hash结构,写起来比较方便。

  • Java
/** * Definition for singly-linked list. * class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public boolean hasCycle(ListNode head) {        Set<ListNode> nodesSeen = new HashSet<>();        while (head != null) {            if (nodesSeen.contains(head)) {                return true;            }             else {                nodesSeen.add(head);            }            head = head.next;        }        return false;    }}

还有一种解法,设置两个指针,一个一次走一步,一个一次走两步,如果存在环,则两个指针会相遇。

  • C++
/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    bool hasCycle(ListNode *head) {        ListNode *slow = head, *fast = head;        while (fast && fast->next) {            slow = slow->next;            fast = fast->next->next;            if (slow == fast) return true;        }        return false;    }};
  • Java
/** * Definition for singly-linked list. * class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public boolean hasCycle(ListNode head) {        ListNode slow = head, fast = head;        while (fast != null && fast.next != null) {            slow = slow.next;            fast = fast.next.next;            if (slow == fast) return true;        }        return false;    }
原创粉丝点击