判断回文

12、给定一个单链表(无环),请判断是否是回文结构。在删除倒数第K个节点后,是否为回文结构。

(回文结构:从头到尾遍历节点的值序列结果,与从尾到头遍历的值序列结果是一样的)

要求: 要考虑时间复杂度和空间复杂度

 

示例 1:

输入: 1->8->4->4->8->1, K=3

输出: true, true

示例 2:

输入: 1->2->5->2->1, K=2

输出: true, false

示例 3:

输入: 1->2->5->3->2->1, K=3

输出: false, true

//12、给定一个单链表(无环),请判断是否是回文结构。在删除倒数第K个节点后,是否为回文结构。
//(回文结构:从头到尾遍历节点的值序列结果,与从尾到头遍历的值序列结果是一样的)
////要求: 要考虑时间复杂度和空间复杂度
// 1->8->4->4->8->1, K=3
// true, true

//思路: 将链表的头和尾分别向中间靠拢,进行判断是否相等,若有一个不相等则不是回文
#include <iostream>
#include <list>
#include <iterator>
using namespace std;

class S
{
public:
    // 判断回文函数,是返回true,不是返回false
    bool check(list<int> list_1)
    {
        bool flag = true;
        //l_end是链表最后一个元素的位置

        list<int>::iterator l_begin = list_1.begin(), l_end = --list_1.end();
        for(int i = 0; i< list_1.size()/2; i++)
        {
            if (*l_begin != *l_end)
            {
                flag = false;
            }
            else
            {
                l_begin++;
                l_end--;
            }
        }
        return flag;
    }

    // 删除链表倒数第K个元素
    void modifyList(list<int> &list_1, int k)
    {
        list<int>::iterator l_end = list_1.end(); // l_end是尾后迭代器
        while(k--)  // 找到第k个元素的位置
        {
           l_end--;
        }
        list_1.erase(l_end);// 删除倒数第k个元素
    }
    //输出结果
    void Print(bool flag)
    {
        if (flag)
            cout <<"true";
        else
            cout << "false";
    }
};


//  1,8,4,4,8,1 k=3,  true, true
//  1,2,5,2,1 k=2 true, false
//  1,2,5,3,2,1, k=3, false, true
int main()
{
    S s;
    list<int> list_1={1,8,4,4,8,1};

    int k =3;

    //判断是否是回文
    bool flag = s.check(list_1);
    // 删除链表倒数第K个元素
    s.modifyList(list_1,k);
    bool flag2 = s.check(list_1);

    //输出
    s.Print(flag);
    cout << ",";
    s.Print(flag2);
    return 0;
}

 

原文地址:https://www.cnblogs.com/xiaokang01/p/12366654.html