LeetCode 234. 回文链表 | C语言版

LeetCode 234. 回文链表 | C语言版

    • LeetCode 234. 回文链表
      • 题目描述
      • 解题思路
        • 思路一:使用快慢双指针
          • 代码实现
          • 运行结果
          • 参考文章:[https://leetcode.cn/problems/palindrome-linked-list/solutions/1011052/dai-ma-sui-xiang-lu-234-hui-wen-lian-bia-qs0k/?q=%E4%BB%A3%E7%A0%81%E9%9A%8F%E6%83%B3%E5%BD%95&orderBy=most_relevant](https://leetcode.cn/problems/palindrome-linked-list/solutions/1011052/dai-ma-sui-xiang-lu-234-hui-wen-lian-bia-qs0k/?q=%E4%BB%A3%E7%A0%81%E9%9A%8F%E6%83%B3%E5%BD%95&orderBy=most_relevant)
        • 思路二:减少遍历节点数
          • 代码实现
          • 运行结果
          • 参考文章:[]()

LeetCode 234. 回文链表

题目描述

题目地址:234. 回文链表
给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。
LeetCode 234. 回文链表 | C语言版_第1张图片

解题思路

思路一:使用快慢双指针
代码实现
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
bool isPalindrome(struct ListNode* head){
    //回文链表:链表的节点顺序从前往后看和从后往前看是相同的(前半段反转后和后半段是相同的)
    //使用快慢双指针

    if(head==NULL || head->next==NULL) return true;
    //慢指针,找到链表中间位置,分割链表
    struct ListNode* slow=head;
    struct ListNode* fast=head;
    //记录慢指针的前一个节点,用来分割链表
    struct ListNode* pre=head;

    //先将链表分为前后两部分
    while(fast && fast->next){
        pre=slow;
        slow=slow->next;
        fast=fast->next->next;
    }
    //分割链表
    pre->next=NULL;

    //前半部段
    struct ListNode* cur1=head;

    //反转后半部段(如果链表总长度是奇数,后半段比前半段多一个节点)
    //保存cur的下一个节点
    struct ListNode* temp;
    struct ListNode* cur=slow;
    struct ListNode* prel=NULL;

    while(cur){
        //保存cur的下一个节点,保证在修改过程中不断链
        temp=cur->next;
        //将cur的指针域指向pre
        cur->next=prel;

        //更新pre和cur指针(向右移动)
        prel=cur;
        cur=temp;
    }
    struct ListNode* cur2=prel;



    //比较链表的前后两段
    while(cur1){
        if(cur1->val!=cur2->val) return false;
        cur1=cur1->next;
        cur2=cur2->next;
    }
    //前半段和反转的后半段完全相同说明链表是回文链表
    return true;
}
运行结果

LeetCode 234. 回文链表 | C语言版_第2张图片

参考文章:https://leetcode.cn/problems/palindrome-linked-list/solutions/1011052/dai-ma-sui-xiang-lu-234-hui-wen-lian-bia-qs0k/?q=%E4%BB%A3%E7%A0%81%E9%9A%8F%E6%83%B3%E5%BD%95&orderBy=most_relevant
思路二:减少遍历节点数
代码实现
在这里插入代码片
运行结果
参考文章:

在这里插入图片描述

你可能感兴趣的:(算法,链表,leetcode,c语言)