这里用了三种方法:
list, stack,和快慢指针结合stack,前两个方法速度都很慢,最后一个快了很多,代码能力太差,有时间重写一遍。
另外还有原地的o(1)的实现,reverse,还不会,太饿了。
参考:https://www.cnblogs.com/grandyang/p/4635425.html
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
// list<int> l;
// // if(head == NULL) return false;
// while(head != NULL){
// l.push_back(head->val);
// head = head->next;
// }
// while(l.size() > 1){
// if(l.front() != l.back())
// return false;
// else{
// l.pop_front();
// l.pop_back();
// }
// }
// return true;
// if(head == NULL)
// return true;
// stack<int> s;
// ListNode* push_node = head;
// ListNode* pop_node = head;
// while(push_node != NULL){
// s.push(push_node->val);
// push_node = push_node->next;
// }
// while(!s.empty()){
// if(s.top() != pop_node->val)
// return false;
// else{
// s.pop();
// pop_node = pop_node->next;
// }
// }
// return true;
//用快慢指针找中点,节省一半的时间
if (head == NULL || head->next == NULL)
return true;
stack<int> s;
ListNode *slow = head;
ListNode *fast = head;
while (fast->next && fast->next->next) {
s.push(slow->val);
slow = slow->next;
fast = fast->next->next;
}
if (fast->next != NULL) {//如果不是最后一个节点,那么总共有偶数个节点,stack的顶部是前一半的最后
s.push(slow->val);
}
while (slow->next != NULL) {
slow = slow->next;
if (s.top() != slow->val)
return false;
else {
s.pop();
}
}
return true;
}
};
快慢指针:
a b c d e f
1 1
或者
a b c d e
1 1