-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathisPalindrome.h
More file actions
70 lines (60 loc) · 1.7 KB
/
isPalindrome.h
File metadata and controls
70 lines (60 loc) · 1.7 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
67
68
69
70
//
// isPalindrome.h
// linkedList
//
// Created by junl on 2019/7/17.
// Copyright © 2019 junl. All rights reserved.
//
#ifndef isPalindrome_h
#define isPalindrome_h
#include "reverseList.h"
namespace leetcode {
/*
234.请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
ListNode* findMiddleNode(ListNode *head){
ListNode *fast,*slow;
fast = slow = head;
while (fast && fast ->next) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
bool isPalindrome(ListNode* head) {
if (!head)
return false;
if (!head->next)
return true;
ListNode *pMid = findMiddleNode(head);
//翻转
ListNode *pRev = reverseList(pMid);
for(;head!=pMid; head=head->next, pRev=pRev->next) {
if (head->val != pRev->val) {
return false;
}
}
return true;
}
void test_isPalindrome(){
singlyLinkedList ll;
ll.insertTail(1);
ll.insertTail(2);
ll.insertTail(2);
ll.insertTail(2);
ll.insertTail(1);
std::cout << "test_isPalindrome: " << isPalindrome(ll.start())<<std::endl;
}
}
#endif /* isPalindrome_h */