File tree 1 file changed +46
-0
lines changed
1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* ------------------------
2
+ Time Complexity: O(n)
3
+ Space Complexity: O(1)
4
+ --------------------------*/
5
+
6
+ class Solution {
7
+ public:
8
+ ListNode* reverse (ListNode* head){
9
+ ListNode* prev = NULL ;
10
+ ListNode* curr = head;
11
+ while (curr){
12
+ ListNode* nex = curr -> next;
13
+ curr -> next = prev;
14
+ prev = curr;
15
+ curr = nex;
16
+ }
17
+ return prev;
18
+ }
19
+
20
+ bool isPalindrome (ListNode* head) {
21
+
22
+ if (head == NULL || head -> next == NULL ){
23
+ return true ;
24
+ }
25
+
26
+ ListNode* fast = head;
27
+ ListNode* slow = head;
28
+ while (fast && fast -> next){
29
+ slow = slow -> next;
30
+ fast = (fast -> next) -> next;
31
+ }
32
+
33
+ ListNode* reversedList = reverse (slow);
34
+ while (reversedList){
35
+ if (head -> val != reversedList -> val) return false ;
36
+ head = head -> next;
37
+ reversedList = reversedList -> next;
38
+ }
39
+ return true ;
40
+ }
41
+ };
42
+
43
+ /*
44
+ Question Link: https://leetcode.com/problems/palindrome-linked-list/
45
+ Author: M.R.Naganathan
46
+ */
You can’t perform that action at this time.
0 commit comments