第一种方法:都放入数组中,双指针从两边向中间扫描对比,空间复杂度O(n)
第二种方法:第一次扫描放入栈中,第二次扫描的时候与出栈的元素对比,空间复杂度O(n)
第三种方法:递归,空间复杂度O(n)
链表逆序输出节点的代码如下:
void nixu(ListNode* head) {
if (head == NULL) return ;
nixu(head->next);
cout << head->val << endl;
}
这道题的思路:递归从后往前遍历,p指针从前往后遍历,依个比较
class Solution {
public:
ListNode *temp; //temp从前往后遍历
bool huiwen(ListNode* head);
bool isPalindrome(ListNode* head) {
if (head == NULL || head->next == NULL) return true;
temp = head;
return huiwen(head);
}
};
bool Solution::huiwen(ListNode* head){
//代码是难点!!
if (head == NULL) return true;
int a = huiwen(head->next) && (head->val == temp->val);
temp = temp->next;
return a;
}
第四种方法:将后半部分逆序,然后跟前半部分对比,空间复杂度O(1)
class Solution {
public:
void reverse (ListNode *left, ListNode *right);
int judge (ListNode *left, ListNode *right);
int flag = 1; //不是回文返回0
bool isPalindrome(ListNode* head) {
if (head == NULL || head->next == NULL) return true;
//快慢指针找中点,fast移动到最后一个位置即可,不用移动到NULL!!!
ListNode *fast = head, *slow = head;
while (fast->next != NULL && fast->next->next != NULL){
fast = fast->next->next;
slow = slow->next;
}
if (fast->next != NULL) fast = fast->next; //fast指向结尾
//后半部分链表反转
reverse(slow, fast);
//扫描判断是否是回文,修改flag值
judge(head, fast);
//恢复后半部分
reverse(fast, slow);
return flag;
}
};
void Solution::reverse(ListNode *left, ListNode *right){
//反转链表是难点!!!
if (left->next == NULL) return ;
ListNode *pre = left, *p = left->next, *after = left->next->next;
pre->next = NULL;
while (p != NULL){
p->next = pre;
pre = p;
p = after;
if (after != NULL)
after = after->next;
}
}
int Solution::judge (ListNode *left, ListNode *right){
while (flag && left != NULL && right != NULL){
if (left -> val != right->val) flag = 0;
left = left->next;
right = right->next;
}
return flag;
}