import random class Node: def __init__(self): self.data = None # contains the data self.nextNode = None # contains the reference to the next node # create a linked list without a cycle nonCycle = Node() nonCycle.data = 1 current = nonCycle for i in range(2,10): new_node = Node() new_node.data = i current.nextNode = new_node current = new_node # create a list with a cycle cycle = Node() cycle.data = 1 current = cycle four = None for i in range(2,8): new_node = Node() new_node.data = i current.nextNode = new_node current = new_node if i == 4: four = new_node if i == 7: new_node.nextNode = four def detectCycle(head): toReturn = None foundCycle = False current = head while current.nextNode and not foundCycle: if not hashMap.get(current): hashMap[current] = 1 current = current.nextNode else: print "Already in: " + str(current.data) foundCycle = True toReturn = current return toReturn print detectCycle(nonCycle) print detectCycle(cycle)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question