程序员面试金典 <Cracking the Coding Interview> 面试题 02.06. 回文链表 双指针 数组

地址  https://leetcode-cn.com/problems/palindrome-linked-list-lcci/

编写一个函数,检查输入的链表是否是回文的。

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

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

解答

由于指针的逆向查找操作比较弱

考虑将其转化成vector,然后使用双指针检查是否是回文

双指针逐步向中间靠拢,检测两侧有无不相同的状态

如图

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool Check(vector<int>& v){
        int l = 0;int r = v.size()-1;
        while(l<r){
            if(v[l]!=v[r]) return false;
            l++;r--;
        }
        return true;
    }
    bool isPalindrome(ListNode* head) {
        if(head==NULL) return true;
        vector<int> vv;
        while(head!=NULL){
            vv.push_back(head->val);
            head=head->next;
        }
        return Check(vv);
    }
};
作 者: itdef
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
阿里打赏 微信打赏
原文地址:https://www.cnblogs.com/itdef/p/14460554.html