给你一个单链表的头节点 head
,请你判断该链表是否为回文链表。如果是,返回 true
;否则,返回 false
。
输入:head = [1,2,2,1] 输出:true
不能用反转链表,因为链表只有一条,反转之后还是那一条,并没有复制新的一条链表,是错误做法,除非自己花精力自己再复制一下这个链表。
方法一:将值复制在数组中再采用双指针(因为链表只能单向遍历,不能双向遍历)
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head == NULL ) return false;
vector<int> vals;
while(head != NULL){
vals.push_back(head -> val);
head = head -> next;
}
for(int i = 0 , j = vals.size() -1 ; i < vals.size() ; i++ , j--){
if(vals[i] != vals[j]) return false;
}
return true;
}
};
方法二:递归(和反转不一样,递归式用一个全局变量存链表的头节点,然后和归的节点比较)
要点: if(!reserveList(head -> next)) 归的布尔,将归作为一种判断而不是返回头节点。,因为不需要知道这个链表的尾节点。
只要有一个相等,直接全部都是false返回,如果相等,则一直返回true
class Solution {
public:
ListNode* frontPoint;
bool isPalindrome(ListNode* head) {
if(head == NULL ) return false;
frontPoint = head;
return reserveList(head);
}
bool reserveList(ListNode* head){
if(head != NULL){
if(!reserveList(head -> next)) return false;
if(frontPoint -> val != head -> val) return false;
frontPoint = frontPoint -> next;
}
return true;
}
};
方法三:栈(利用先进后出得原则)
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head == NULL ) return false;
stack<int> stack;
ListNode* newhead = head ;
while(head != NULL){
stack.push(head -> val);
head = head -> next;
}
while(!stack.empty()){
if(stack.top() != newhead -> val) return false;
stack.pop();
newhead = newhead -> next;
}
return true;
}
};