刷题-Leetcode-234. 回文链表

234. 回文链表

题目链接

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-linked-list/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题目描述

请判断一个链表是否为回文链表。

示例 1:

输入: 1->2
输出: false
示例 2:

输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

题目分析

做完力扣206再来做这题

  • 方法一:双指针(数组)空间o(n)-链表的数字放进数组里 第一个指针在头,第二个指针在尾
    将值复制到数组中后用双指针法
    1. 复制链表值到数组列表中。
    2. 使用双指针法判断是否为回文。
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        vector<int> nums;
        ListNode* dummy = head;
        while(dummy){
            nums.push_back(dummy->val);
            dummy = dummy->next;
        }
        int n = nums.size();
        int left = 0;
        int right = n - 1;
        while(left < right){
            if(nums[left] != nums[right]){
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
};
  • 方法二:递归+双指针 递归栈空间o(n)
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode * global;
    bool isPalindrome(ListNode* head) {
        global = head;
        return recursion(head);
    }
    bool recursion(ListNode* head){
        if(!head){
            return true;
        }
        if(!recursion(head->next)){
            return false;
        }
        if(global->val != head->val){
            return false;
        }
        global = global->next;//注意 别忘了
        return true;
    }
};
  • 方法三:栈-空间o(n)栈底对应head 栈尾对应tail 从链表head 开始 与 栈顶判断
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        stack<ListNode*> stack;//栈内存储指针
        ListNode * dummy = head;
        while(dummy){
            stack.push(dummy);
            dummy = dummy->next;
        }
        dummy = head;
        while(dummy){
            if(dummy->val != stack.top()->val){
                return false;
            }
            dummy = dummy->next;
            stack.pop();
        }
        return true;
    }
};

进阶

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值