栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

面试题 02.06. 回文链表(C实现)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

面试题 02.06. 回文链表(C实现)

题目

题目链接:面试题 02.06. 回文链表


思路

先 找到回文链表的中间结点;
再 逆置中间节点往后的链表;
然后从回文链表的头开始遍历 和逆置后的链表一个一个比;
假如相等就迭代,知道遇到空;证明是回文链表
假如不相等那么就一定不是回文链表

//快慢指针找中间结点
struct ListNode* middleNode(struct ListNode* head)
{
    if(head == NULL || head->next ==NULL) return head;
    struct ListNode* slow = head;
    struct ListNode* fast = head;

    while(fast && fast->next)
    {
        slow = slow->next;
        fast = fast->next->next;
    }
    return slow;
}

//头插法逆置
struct ListNode* reverser(struct ListNode* head)
{
    if(head == NULL || head->next == NULL) return head;
    struct ListNode* cur = head;
    struct ListNode* newHead = NULL;

    while(cur)
    {
        struct ListNode* curNext = cur->next;

        cur->next = newHead;
        newHead = cur;

        cur = curNext;
    }
    return newHead;
}


bool isPalindrome(struct ListNode* head){
    //先找到回文链表的中间节点
    struct ListNode* mid = middleNode(head);

    //找到中间结点后,逆置中间结点往后的链表
    struct ListNode* reverserNode = reverser(mid);
    
	//分别用 curFront 和 curMid 指向回文链表的头,和逆置链表的头
    struct ListNode* curFront = head;
    struct ListNode* curMid = reverserNode;

    while( curFront && curMid)
    {	//不相等就直接返回了,肯定不是回文链表
        if(curFront->val != curMid->val)
        {
             return false;           
        }
        else
        {//相等就迭代
            curFront = curFront->next;
            curMid = curMid->next;           
        }
    }
    return true;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/352863.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号