MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / is_palindrome

Function is_palindrome

data_structures/linked_list/is_palindrome.py:12–65  ·  view source on GitHub ↗

Check if a linked list is a palindrome. Args: head: The head of the linked list. Returns: bool: True if the linked list is a palindrome, False otherwise. Examples: >>> is_palindrome(None) True >>> is_palindrome(ListNode(1)) True

(head: ListNode | None)

Source from the content-addressed store, hash-verified

10
11
12def is_palindrome(head: ListNode | None) -> bool:
13 """
14 Check if a linked list is a palindrome.
15
16 Args:
17 head: The head of the linked list.
18
19 Returns:
20 bool: True if the linked list is a palindrome, False otherwise.
21
22 Examples:
23 >>> is_palindrome(None)
24 True
25
26 >>> is_palindrome(ListNode(1))
27 True
28
29 >>> is_palindrome(ListNode(1, ListNode(2)))
30 False
31
32 >>> is_palindrome(ListNode(1, ListNode(2, ListNode(1))))
33 True
34
35 >>> is_palindrome(ListNode(1, ListNode(2, ListNode(2, ListNode(1)))))
36 True
37 """
38 if not head:
39 return True
40 # split the list to two parts
41 fast: ListNode | None = head.next_node
42 slow: ListNode | None = head
43 while fast and fast.next_node:
44 fast = fast.next_node.next_node
45 slow = slow.next_node if slow else None
46 if slow:
47 # slow will always be defined,
48 # adding this check to resolve mypy static check
49 second = slow.next_node
50 slow.next_node = None # Don't forget here! But forget still works!
51 # reverse the second part
52 node: ListNode | None = None
53 while second:
54 nxt = second.next_node
55 second.next_node = node
56 node = second
57 second = nxt
58 # compare two parts
59 # second part has the same or one less node
60 while node and head:
61 if node.val != head.val:
62 return False
63 node = node.next_node
64 head = head.next_node
65 return True
66
67
68def is_palindrome_stack(head: ListNode | None) -> bool:

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected