Skip to content

Instantly share code, notes, and snippets.

@kciter
Last active August 29, 2015 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kciter/10826364 to your computer and use it in GitHub Desktop.
Save kciter/10826364 to your computer and use it in GitHub Desktop.
매일코딩 4월 16일 문제: http://oj.leetcode.com/problems/linked-list-cycle/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#include <map>
class Solution {
public:
bool hasCycle(ListNode *head) {
if (head == NULL) return false;
std::map<ListNode*, bool> table;
while (!table[head]) {
table[head] = true;
if (head->next == NULL) {
return false;
}
head = head->next;
}
return true;
}
};
/**
* 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) {
if (head == null) return false;
Map<ListNode, Boolean> table = new HashMap<ListNode, Boolean>();
while (table.get(head) == null) {
table.put(head, true);
if (head.next == null) {
return false;
}
head = head.next;
}
return true;
}
}
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a boolean
def hasCycle(self, head):
if head == None:
return False
table = dict();
while head not in table:
table[head] = True
if head.next == None:
return False
head = head.next
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment