💐The Begin💐点点关注,收藏不迷路💐
|
给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。
示例 1:
输入:head = [1,2,2,1]
输出:true
示例 2:
输入:head = [1,2]
输出:false
提示:
链表中节点数目在范围[1, 105] 内
0 <= Node.val <= 9
进阶:你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
// 定义单链表节点
struct ListNode {
int val;
struct ListNode *next;
};
// 辅助递归函数,用于比较链表节点
bool isPalindromeHelper(struct ListNode** head, struct ListNode* tail) {
if (tail == NULL) {
return true;
}
bool isPal = isPalindromeHelper(head, tail->next);
if (!isPal) {
return false;
}
bool result = ((*head)->val == tail->val);
(*head) = (*head)->next;
return result;
}
// 判断是否为回文链表函数
bool isPalindrome(struct ListNode* head) {
return isPalindromeHelper(&head, head);
}
💐The End💐点点关注,收藏不迷路💐
|
因篇幅问题不能全部显示,请点此查看更多更全内容