LeetCode 234
请判断一个链表是否为回文链表。
示例 1:
1
2输入: 1->2
输出: false示例 2:
1
2输入: 1->2->2->1
输出: true
解决参照之前练习题:查找中间节点 和 反转列表 应用结合起来: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
44class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL||head->next==NULL)
return head;
ListNode *p=reverseList(head->next);
head->next->next=head;
head->next=NULL;
return p;
}
ListNode* middleNode(ListNode* head) {
if (head == NULL)
return head;
ListNode *slow = head;
ListNode *fast = head;
while (fast && fast->next){
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
bool isPalindrome(ListNode* head) {
ListNode *mid = middleNode(head);
ListNode *slow = reverseList(mid);
while(head&&slow)
{
if(head->val!=slow->val)
return false;
else
{
head=head->next;
slow=slow->next;
}
}
return true;
}
};