C语言/数据结构——(链表的回文结构)

一.前言

今天在牛客网上刷到了一道链表题------链表的回文结构https://www.nowcoder.com/practice/d281619e4b3e4a60a2cc66ea32855bfa?,巧合的是它的解题思路恰好是我们一起分享过两道链表题的汇总。这两道题分别是反转链表和链表的中间节点。废话不多数,让我们直接进入今天的正文环节吧。

二.正文

1.1题目描述

1.2题目分析

对于这道题,我们的思路是先找到链表的中间节点,然后将中间节点及之后的链表进行逆置,这样就可以得到两个链表的头节点。并让这两个链表的元素依次比较大小,如果元素依次相同,则返回true,否者返回false。

就比如:1->2->2->1

对于反转链表和找到中间节点可以看我写的文章。下面是对应其链接:

反转链表:https://blog.csdn.net/yiqingaa/article/details/138376042?

查找中间节点:https://leetcode.cn/problems/middle-of-the-linked-list

1.3代码实现

cpp 复制代码
/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
 typedef struct ListNode ListNode;
class PalindromeList {
public:
ListNode* middleNode(struct ListNode* head) 
{
    ListNode* slow;
    ListNode* fast;
    fast=slow=head;
    while((fast!=NULL)&&(fast->next!=NULL))
    {
        slow=slow->next;
        fast=fast->next->next;
    }
    return slow;
}
typedef struct ListNode ListNode;
ListNode* ReverseList( ListNode* head)
{
// if(head==NULL)
  //  return NULL;
    ListNode*pcur,*prev,*pnext;
    ListNode* phead=(ListNode*)malloc(sizeof(ListNode));
    phead->next=head;
    pcur=head;prev=phead;pnext=pcur->next;
    while(pcur!=NULL)
    {
        pcur->next=prev;
        prev=pcur;
        pcur=pnext;
        if(pnext!=NULL)
        pnext=pnext->next;
    }
    head->next=NULL;
    free(phead);
    phead=NULL;
    return prev;
}
    bool chkPalindrome(ListNode* A) {
        // write code here
ListNode* mid=middleNode(A);
ListNode* remid= ReverseList(mid);
while(remid&&A)
{
    if(A->val!=remid->val)
     return false;
     else
     {
        A=A->next;
        remid=remid->next;
     }

}
return true;
    } 
};

值得注意的是,以上代码是在牛客网上运行的。

三.结言

今天的题目就分享到这了,帅哥美女们,我们下次再见喽,拜拜~

相关推荐
祈安_3 天前
C语言内存函数
c语言·后端
郑州光合科技余经理5 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1235 天前
matlab画图工具
开发语言·matlab
dustcell.5 天前
haproxy七层代理
java·开发语言·前端
norlan_jame5 天前
C-PHY与D-PHY差异
c语言·开发语言
琢磨先生David5 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
多恩Stone5 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054965 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
czy87874755 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
遥遥江上月5 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js