
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Linked List Cycle in Python
Consider we have a linked list, and we have to check whether there is any cycle or not. To represent the cycle in the given linked list, we will use one integer pointer called pos. This pos represents a position in the linked list where tail is connected. So if pos is -1, then there is no cycle present in the linked list. For example, the linked list is like [5, 3, 2, 0, -4, 7], and pos = 1. So there is a cycle, and tail is connected to the second node.
To solve this, we will follow these steps −
- Take one set as hash set H
- while head is not null −
- if head is present in H, then return true
- add head into H
- head := next of head
- return False
Example
Let us see the following implementation to get better understanding −
class ListNode: def __init__(self, data, next = None): self.data = data self.next = next def make_list(elements): head = ListNode(elements[0]) for element in elements[1:]: ptr = head while ptr.next: ptr = ptr.next ptr.next = ListNode(element) return head def get_node(head, pos): if pos != -1: p = 0 ptr = head while p < pos: ptr = ptr.next p += 1 return ptr class Solution(object): def hasCycle(self, head): hashS = set() while head: if head in hashS: return True hashS.add(head) head = head.next return False head = make_list([5,3,2,0,-4,7]) last_node = get_node(head, 5) pos = 1 last_node.next = get_node(head, pos) ob1 = Solution() print(ob1.hasCycle(head))
Input
List = [5,3,2,0,-4,7] Pos = 1
Output
True
- Related Articles
- Linked List Cycle II in C++
- Python Program to Detect the Cycle in a Linked List
- Palindrome Linked List in Python
- Reverse Linked List in Python
- Program to find linked list intersection from two linked list in Python
- Odd Even Linked List in Python
- Python Circular Linked List Program
- Length of a Linked List in Python
- A strictly increasing linked list in Python
- Delete Node in a Linked List in Python
- Program to reverse a linked list in Python
- Convert singly linked list into circular linked list in C++
- Convert singly linked list into XOR linked list in C++
- Program to find folded list from a given linked list in Python
- Program to swap nodes in a linked list in Python

Advertisements