题目描述:

在这里插入图片描述

题解一:deque

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
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head == nullptr) return false;
//使用双端队列
deque<int> deq;
while(head != nullptr)
{
deq.push_back(head->val);
head = head->next;
}
while(!deq.empty())
{
if(deq.front() != deq.back())
{
return false;
}
deq.pop_front();
if(!deq.empty())
{
deq.pop_back();
}
}
return true;
}
};

在这里插入图片描述

题解二:stack

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
class Solution {
private:
int getlen(ListNode* head)
{
int count = 0;
while(head != nullptr)
{
++count;
head = head->next;
}
return count;
}
public:
bool isPalindrome(ListNode* head) {
if(head == nullptr) return false;
stack<int> st;
ListNode* ptr = head;
int half_len = getlen(head) / 2;
bool tag = getlen(head) % 2 == 1 ? true : false;
while(half_len--)
{
st.push(ptr->val);
ptr = ptr->next;
}
if(tag)
{
ptr = ptr->next;
}
while(!st.empty() && ptr != nullptr && st.top() == ptr->val)
{
st.pop();
ptr = ptr->next;
}
if(st.empty())
{
return true;
}
return false;
}
};

在这里插入图片描述