LeetCode_234_回文链表
廖家龙 用心听,不照做

题目描述:

1
2
3
4
5
6
7
8
请判断一个链表是否为回文链表。

示例:
输入: 1->2
输出: false

输入: 1->2->2->1
输出: true

解法1:双指针

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
/**
* 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) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {

vector<int> vals;

//复制链表值到数组列表中
while (head != nullptr) {

vals.emplace_back(head->val);
head = head->next;
}

//使用双指针法判断是否为回文
for (int i = 0, j = (int)vals.size() - 1; i < j; ++i, --j) {

if (vals[i] != vals[j]) {
return false;
}
}

return true;
}
};