234. Palindrome Linked List

题目:

Given the head of a singly linked list, return true if it is a palindrome.

 

Example 1:

Input: head = [1,2,2,1]
Output: true

Example 2:

Input: head = [1,2]
Output: false

 

Constraints:

  • The number of nodes in the list is in the range [1, 105].
  • 0 <= Node.val <= 9

 

Follow up: Could you do it in O(n) time and O(1) space?

 

 

 

思路1:

很简单,先用容器把每个node存下来,然后对于容器使用两个pointer,一个从头到尾一个从尾到头,检查是否回文即可。但是要消耗空间复杂度。

 

 

 

 

代码1:

/**
 * 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:
    //iterative
    bool isPalindrome(ListNode* head) {
        vector<int> record;
        while(head)
        {
            record.push_back(head->val);
            head=head->next;
        }
        for(int i=0,j=record.size()-1;i<=j;i++,j--)
        {
            if(record[i]!=record[j])
                return false;
        }
        return true;
    }
};

 

 

 

 

 

思路2:

理论上其实也是O(n)的空间复杂度,因为是递归的,其实消耗了栈空间。首先用一个额外的node来记录当前的位置。遍历List,如果当前node是空则返回true,说明我们到了尾部;之后记录下一个和当前是否回文,然后往下移一格即可。总的来说是一道比较老的题,思路想清楚了即可。

 

 

 

 

代码2:

class Solution {
public:
    //recursive
    ListNode* temp;
    bool isPalindrome(ListNode* head)
    {
        temp=head;
        return check(temp);
    }
    bool check(ListNode* cur)
    {
        if(!cur)
            return true;
        bool flag = check(cur->next) && cur->val==temp->val;
        temp=temp->next;
        return flag;
    }

};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值