LeetCode //C - 234. Palindrome Linked List

234. Palindrome Linked List

Given the head of a singly linked list, return true if it is a palindrome or false otherwise.
 

Example 1:

在这里插入图片描述

Input: head = [1,2,2,1]
Output: true

Example 2:

在这里插入图片描述

Input: head = [1,2]
Output: false

Constraints:
  • The number of nodes in the list is in the range [ 1 , 1 0 5 ] [1, 10^5] [1,105].
  • 0 <= Node.val <= 9

From: LeetCode
Link: 234. Palindrome Linked List


Solution:

Ideas:
  1. Find the middle of the linked list.
  2. Reverse the second half of the linked list.
  3. Compare the first half with the reversed second half.
  4. If all the values match, it’s a palindrome.
  5. Re-reverse the second half to restore the original list (optional).
Code:
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
bool isPalindrome(struct ListNode* head) {
    struct ListNode *fast = head, *slow = head;
    struct ListNode *prev, *temp;

    // Find the middle of the linked list
    while (fast && fast->next) {
        fast = fast->next->next;
        slow = slow->next;
    }
    
    // Reverse the second half of the list
    prev = NULL;
    while (slow) {
        temp = slow->next;
        slow->next = prev;
        prev = slow;
        slow = temp;
    }
    
    // Compare the first half and the reversed second half
    while (prev) {
        if (head->val != prev->val) {
            return false;
        }
        head = head->next;
        prev = prev->next;
    }

    return true;
}

相关推荐

  1. LeetCode 550, 380, 234

    2024-03-13 15:52:06       13 阅读
  2. 234.回文链表

    2024-03-13 15:52:06       17 阅读
  3. 234. 回文链表

    2024-03-13 15:52:06       11 阅读
  4. leetcode234-Palindrome Linked List

    2024-03-13 15:52:06       12 阅读
  5. 234. 回文链表

    2024-03-13 15:52:06       11 阅读
  6. Leetcode274

    2024-03-13 15:52:06       13 阅读

最近更新

  1. 贪心算法合集一

    2024-03-13 15:52:06       0 阅读
  2. 索引知识总结

    2024-03-13 15:52:06       0 阅读
  3. Oracle怎么实现RSA加密解密

    2024-03-13 15:52:06       0 阅读
  4. 前端判断场景和方式

    2024-03-13 15:52:06       1 阅读

热门阅读

  1. 面视题之——悲观锁和乐观锁

    2024-03-13 15:52:06       22 阅读
  2. HTTP协议相关面试知识

    2024-03-13 15:52:06       24 阅读
  3. MongoDB学习笔记

    2024-03-13 15:52:06       23 阅读
  4. 【项目实践】Pyside6+Qtdesigner:登录窗体设计

    2024-03-13 15:52:06       21 阅读
  5. SQL 中避免使用 != 或 <>

    2024-03-13 15:52:06       23 阅读
  6. unityAB包管理(远程下载)

    2024-03-13 15:52:06       21 阅读
  7. 【蓝桥杯】分糖果

    2024-03-13 15:52:06       21 阅读
  8. 前端框架发展史

    2024-03-13 15:52:06       20 阅读