-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPalindrome Linked List.cpp
104 lines (93 loc) · 2.61 KB
/
Palindrome Linked List.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// Problem Statement Link - https://leetcode.com/problems/palindrome-linked-list/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
// Using stack
// Time : O(n); space : O(n)
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head == NULL or head->next == NULL)
{
return true;
}
stack <int> s;
ListNode* temp = head;
while(temp != NULL)
{
s.push(temp->val);
temp=temp->next;
}
temp = head;
while(temp != NULL)
{
int topOfStack = s.top();
s.pop();
if(topOfStack != temp->val)
return false;
temp=temp->next;
}
return true;
}
};
// Time : O(n); space : O(1)
bool isPalindrome(ListNode* head) {
if(head != NULL || head->next == NULL)
{
return true;
}
if(head->next->next == NULL)
{
return head->val == head->next->val;
}
ListNode *slow = head, *fast = head, *temp1=NULL,*temp2=NULL;
while(fast->next != NULL && fast->next->next != NULL)
{
fast = fast->next->next;
slow = slow->next;
}
fast = slow->next;
while(fast != NULL){
temp1 = fast->next;
fast->next = temp2;
temp2 = fast;
fast = temp1;
}
slow->next = temp2;
fast = slow->next;
slow = head;
while(fast != NULL){
if(fast->val != slow->val)return false;
fast = fast->next;
slow = slow->next;
}
return true;
}
// Recursion
// Time : O(n); space : O(n)
class Solution{
public:
bool isListPalindrome(ListNode* &leftmostNode, ListNode* rightmostNode)
{
if(rightmostNode == NULL)
return true;
bool resultSublist = isListPalindrome(leftmostNode, rightmostNode->next);
if(resultSublist == false)
{
return false;
}
bool result = leftmostNode->val == rightmostNode->val;
leftmostNode = leftmostNode->next;
return result;
}
bool isPalindrome(ListNode* head) {
return isListPalindrome(head, head);
}
};