-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpalindromicLinkedList.cpp
More file actions
66 lines (63 loc) · 1.51 KB
/
Copy pathpalindromicLinkedList.cpp
File metadata and controls
66 lines (63 loc) · 1.51 KB
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
/**
* https://leetcode.com/problems/palindrome-linked-list/
* Linked List, Two Pointers, Stack, Recursion
* Easy
*/
#include <iostream>
using namespace std;
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) {}
};
class Solution {
public:
bool isPalindrome(ListNode* head) {
// make reverse of linked list
ListNode* copy = head;
ListNode* reverseList = new ListNode;
reverseList->val = copy->val;
reverseList->next = nullptr;
while (copy) {
ListNode* newNode = new ListNode;
newNode->val = copy->val;
newNode->next = reverseList;
reverseList = newNode;
copy = copy->next;
}
// compare between reverse linked list and original linked list
while (head && reverseList) {
if (head->val != reverseList->val) {
return false;
}
head = head->next;
reverseList = reverseList->next;
}
return true;
}
};
int main() {
ListNode* head = new ListNode;
ListNode* curr = head;
int num;
cout << "Input Linked List: " << endl;
while (cin >> num && num != -1) {
curr->next = new ListNode(num);
curr = curr->next;
}
ListNode* newHead = head->next;
delete head;
/*
while (newHead) {
cout << newHead->val << ' ';
newHead = newHead->next;
}*/
Solution solution;
if (solution.isPalindrome(newHead)) {
cout << "is palindrome" << endl;
} else {
cout << "is not palindrome" << endl;
}
}