请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *middleNode(struct ListNode *head) {
struct ListNode *slowNode = head;
struct ListNode *fastNode = head;
while (fastNode->next != NULL && fastNode->next->next != NULL) {
fastNode = fastNode->next->next;
slowNode = slowNode->next;
}
return slowNode;
}
struct ListNode * reverseList(struct ListNode *head) {
struct ListNode *preNode = NULL;
struct ListNode *curNode = head;
struct ListNode *tmpNode = NULL;
while (curNode != NULL) {
tmpNode = curNode->next;
curNode->next = preNode;
preNode = curNode;
curNode = tmpNode;
}
return preNode;
}
bool isPalindrome(struct ListNode* head){
if (head == NULL) {
return true;
}
struct ListNode *midNode = middleNode(head);
struct ListNode *firstPart = head;
struct ListNode *secondPart = midNode->next;
secondPart = reverseList(secondPart);
while (secondPart != NULL) {
if (firstPart->val != secondPart->val) {
return false;
}
firstPart = firstPart->next;
secondPart = secondPart->next;
}
return true;
}