File tree Expand file tree Collapse file tree 2 files changed +57
-0
lines changed
Solutions/0234-palindrome-linked-list Expand file tree Collapse file tree 2 files changed +57
-0
lines changed Original file line number Diff line number Diff line change 1+ <p >Given the <code >head</code > of a singly linked list, return <code >true</code ><em > if it is a </em ><span data-keyword =" palindrome-sequence " ><em >palindrome</em ></span ><em > or </em ><code >false</code ><em > otherwise</em >.</p >
2+
3+ <p >  ; </p >
4+ <p ><strong class =" example " >Example 1:</strong ></p >
5+ <img alt =" " src =" https://assets.leetcode.com/uploads/2021/03/03/pal1linked-list.jpg " style =" width : 422px ; height : 62px ;" />
6+ <pre >
7+ <strong >Input:</strong > head = [1,2,2,1]
8+ <strong >Output:</strong > true
9+ </pre >
10+
11+ <p ><strong class =" example " >Example 2:</strong ></p >
12+ <img alt =" " src =" https://assets.leetcode.com/uploads/2021/03/03/pal2linked-list.jpg " style =" width : 182px ; height : 62px ;" />
13+ <pre >
14+ <strong >Input:</strong > head = [1,2]
15+ <strong >Output:</strong > false
16+ </pre >
17+
18+ <p >  ; </p >
19+ <p ><strong >Constraints:</strong ></p >
20+
21+ <ul >
22+ <li>The number of nodes in the list is in the range <code>[1, 10<sup>5</sup>]</code>.</li>
23+ <li><code>0 <= Node.val <= 9</code></li>
24+ </ul >
25+
26+ <p >  ; </p >
27+ <strong >Follow up:</strong > Could you do it in <code >O(n)</code > time and <code >O(1)</code > space?
Original file line number Diff line number Diff line change 1+ # Definition for singly-linked list.
2+ # class ListNode:
3+ # def __init__(self, val=0, next=None):
4+ # self.val = val
5+ # self.next = next
6+ class Solution :
7+ def isPalindrome (self , head : Optional [ListNode ]) -> bool :
8+ # slow, fast = head, head.next
9+ # while fast and fast.next:
10+ # slow, fast = slow.next, fast.next.next
11+ # last, current = None, slow.next
12+
13+ # while current:
14+ # tmp = current.next
15+ # current.next = last
16+ # last, current = current, tmp
17+
18+ # while last:
19+ # if last.val != head.val:
20+ # return False
21+ # last, head = last.next, head.next
22+
23+ # return True
24+
25+ dummy = head
26+ nums = []
27+ while dummy :
28+ nums .append (dummy .val )
29+ dummy = dummy .next
30+ return nums == nums [::- 1 ]
You can’t perform that action at this time.
0 commit comments