题目
代码(首刷自解,deque)
有很多种做法,还有一种是快慢指针,将后半段逆序,然后比较
class Solution {
public:
bool isPalindrome(ListNode* head) {
// if(!head->next)
// return true;
deque<int> q;
auto p = head;
while(p) {
q.push_back(p->val);
p = p->next;
}
while(!q.empty()) {
if(q.front() != q.back())
return false;
q.pop_front();
q.pop_back();
}
return true;
}
};
代码(8.10 二刷自解)
这次用的方法是将后半段逆序,比较
class Solution {
public:
bool isPail(ListNode* head) {
auto mid = middle(head);
auto tail = reverse(mid);
while(head != tail && head->next != tail) {
if(head->val != tail->val) {
return false;
}
head = head->next;
tail = tail->next;
}
return head->val == tail->val;
}
ListNode* reverse(ListNode* head) {
if(!head || !head->next)
return head;
auto newHead = reverse(head->next);
head->next->next = head;
head->next = nullptr;
return newHead;
}
ListNode* middle(ListNode* head) {
auto fast = head, slow = head;
while(fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
}
return slow;
}
};
复制到数组
func isPalindrome(head *ListNode) bool {
res := []int{}
for ; head != nil; head = head.Next {
res = append(res, head.Val)
}
n := len(res)
for i, v := range res[:n/2] {
if v != res[n-1-i] {
return false
}
}
return true
}
代码(9.3 三刷自解)
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(!head->next)
return head;
stack<int> sk;
auto p = head;
while(p) {
sk.push(p->val);
p = p->next;
}
while(!sk.empty()) {
if(sk.top() != head->val)
return false;
head = head->next;
sk.pop();
}
return true;
}
};