File tree Expand file tree Collapse file tree 1 file changed +71
-0
lines changed
solutions/234.Palindrome_Linked_List Expand file tree Collapse file tree 1 file changed +71
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * Author: illuz <iilluzen[at]gmail.com>
3
+ * File: AC_recursive_n.cpp
4
+ * Create Date: 2015-07-28 23:56:22
5
+ * Descripton:
6
+ */
7
+
8
+ #include < bits/stdc++.h>
9
+
10
+ using namespace std ;
11
+ const int N = 0 ;
12
+
13
+ // Definition for singly-linked list.
14
+ struct ListNode {
15
+ int val;
16
+ ListNode *next;
17
+ ListNode (int x) : val(x), next(NULL ) {}
18
+ };
19
+
20
+ class Solution {
21
+ public:
22
+ bool isPalindrome (ListNode* head) {
23
+ int len = 0 ;
24
+ ListNode *cur = head;
25
+ while (cur != NULL ) {
26
+ ++len;
27
+ cur = cur->next ;
28
+ }
29
+ cur = head;
30
+ return isPalindromeHelper (cur, len);
31
+ }
32
+ private:
33
+ bool isPalindromeHelper (ListNode* &head, int len) {
34
+ if (len < 2 ) return true ;
35
+ if (len == 2 ) {
36
+ int head_val = head->val ;
37
+ head = head->next ;
38
+ int tail_val = head->val ;
39
+ return head_val == tail_val;
40
+ }
41
+ int head_val = head->val ;
42
+ head = head->next ;
43
+ if (!isPalindromeHelper (head, len - 2 ))
44
+ return false ;
45
+ head = head->next ;
46
+ int tail_val = head->val ;
47
+ return head_val == tail_val;
48
+ }
49
+ };
50
+
51
+ int main () {
52
+ Solution s;
53
+ ListNode l1 (1 );
54
+ ListNode l2 (2 );
55
+ ListNode l3 (3 );
56
+ ListNode l4 (3 );
57
+ ListNode l5 (2 );
58
+ ListNode l6 (1 );
59
+ l1.next = &l2;
60
+ cout << s.isPalindrome (&l1) << endl;
61
+ l2.next = &l3;
62
+ cout << s.isPalindrome (&l1) << endl;
63
+ l3.next = &l4;
64
+ cout << s.isPalindrome (&l1) << endl;
65
+ l4.next = &l5;
66
+ cout << s.isPalindrome (&l1) << endl;
67
+ l5.next = &l6;
68
+ cout << s.isPalindrome (&l1) << endl;
69
+ return 0 ;
70
+ }
71
+
You can’t perform that action at this time.
0 commit comments