每日一练之链表的回文结构

题目描述:

方法一:

找到链表的中间结点。

图片解疑:

从中间结点开始把后面的链表反转。注:详细请看附录链接

图片解疑:

判断头结点的值和尾结点的值是否一样。

代码实例:

cpp 复制代码
/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
#include <cstddef>
#include<stdio.h>
ListNode* middlenode(ListNode* head)
{
    ListNode* fast,*slow;//快慢指针
    fast=slow=head;
    while(fast && fast->next)
    {
        slow=slow->next;//slow走一步
        fast=fast->next->next;//fast走两步
    }
    return slow;//返回中间结点
}
ListNode* reverseList(ListNode* head)
{
    ListNode* n1,*n2,*n3;
    n1=NULL,n2=head,n3=head->next;
    while(n2)
    {
        n2->next=n1;
        n1=n2;
        n2=n3;
        if(n3)
        {
            n3=n3->next;
        }
    }
    return n1;
}
class PalindromeList {
public:
    bool chkPalindrome(ListNode* A) {
        //找中间结点
        ListNode* mid=middlenode(A);
        //反转链表
        ListNode* right=reverseList(mid);//返回的是尾结点
        //遍历和判断
        ListNode* left=A;
        while(right)
        {
            if(left->val != right->val)
            {
                return false;
            }
            left=left->next;
            right=right->next;
        }
        return true;
    }
};

方法二:

创建数组把链表的val值存储进去。

在数组中判断是否为回文结构。

代码实例:

cpp 复制代码
/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
class PalindromeList {
public:
    bool chkPalindrome(ListNode* A) {
        int arr[900]={0};
        ListNode* newnode=A;
        int i=0;
        while(newnode)
        {
            arr[i++]=newnode->val;
            newnode=newnode->next;
        }
        int left=0;
        int right=i-1;
        while(left<right)
        {
            if(arr[left] != arr[right])
            {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
};

完!!

附录:每日一练之反转链表-CSDN博客

相关推荐
m0_547486663 天前
《数据结构教程》全套 PPT课件2026
数据结构
tryxr3 天前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_33 天前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
All for pursuit.3 天前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
All for pursuit.3 天前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
渡我白衣3 天前
HttpRequest与HttpResponse的实现
服务器·数据结构·c++·人工智能·tcp/ip·机器学习·caffe
晴天的雨.9923 天前
【C++算法】和为s的两个数
开发语言·数据结构·c++·算法
无敌贵点大王4 天前
RTThread学习记录11——RT-Thread 设备模型吃透:UART/ADC/PWM/PIN 到底有什么区别?
c语言·stm32·学习·链表
淡海水4 天前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp
Logic1014 天前
C语言/数据结构位运算题解:异或XOR找出时尚聚会中的“独特颜色“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质