[LeetCode] Palindrome Linked List

本文介绍了一种通过反转链表右半部分并比较其与左半部分来判断链表是否为回文的方法。通过实现反转链表的函数,我们能够有效地检查链表的对称性。

The idea is not so obvious at first glance. Since you cannot move from a node back to its previous node in a singly linked list, we choose to reverse the right half of the list and then compare it with the left half. The code is as follows. It shoul be obvious after you run some examples.

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     bool isPalindrome(ListNode* head) {
12         if (!head || !(head -> next)) return true;
13         ListNode* slow = head;
14         ListNode* fast = head;
15         while (fast && fast -> next) {
16             slow = slow -> next;
17             fast = fast -> next -> next;
18         }
19         if (fast) {
20             slow -> next = reverseList(slow -> next);
21             slow = slow -> next;
22         }
23         else slow = reverseList(slow);
24         while (slow) {
25             if (head -> val != slow -> val)
26                 return false;
27             head = head -> next;
28             slow = slow -> next;
29         }
30         return true;
31     }
32 private:
33     ListNode* reverseList(ListNode* node) {
34         ListNode* pre = NULL;
35         while (node) {
36             ListNode* next = node -> next;
37             node -> next = pre;
38             pre = node;
39             node = next;
40         }
41         return pre;
42     }
43 };

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值