[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 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 };

 

目录
相关文章
|
Java
Leetcode 114. Flatten Binary Tree to Linked List
思路也很简单,先把root的左子树(如有)变成单链表 leftlinkedlist,把root的右子树(如有)变成单链表 rightlinkedlist,再把root的右节点变成leftlikedlist,再把rightlinkedlist接到leftlinkedlist后面,代码如下。
44 1
|
C++
Leetcode Copy List with Random Pointer(面试题推荐)
给大家推荐一道leetcode上的面试题,这道题的具体讲解在《剑指offer》的P149页有思路讲解,如果你手头有这本书,建议翻阅。
50 0
Leetcode 19.Remove Nth Node From End of List
删除单链表中的倒数第n个节点,链表中删除节点很简单,但这道题你得先知道要删除哪个节点。在我的解法中,我先采用计数的方式来确定删除第几个节点。另外我在头节点之前额外加了一个节点,这样是为了把删除头节点的特殊情况转换为一般情况,代码如下。
37 0
|
6月前
|
存储 Python
链表(Linked List)详解
链表(Linked List)详解
50 0
|
6月前
|
大数据 Java 程序员
「LeetCode合集」链表(List)及经典问题
「LeetCode合集」链表(List)及经典问题
51 0
|
C++
【PAT甲级 - C++题解】1133 Splitting A Linked List
【PAT甲级 - C++题解】1133 Splitting A Linked List
81 0
|
C++
【PAT甲级 - C++题解】1074 Reversing Linked List
【PAT甲级 - C++题解】1074 Reversing Linked List
72 0
|
机器学习/深度学习 存储 C++
【PAT甲级 - C++题解】1052 Linked List Sorting
【PAT甲级 - C++题解】1052 Linked List Sorting
83 0
LeetCode 141. 环形链表 Linked List Cycle
LeetCode 141. 环形链表 Linked List Cycle
二叉树(Binary Tree)的二叉链表(Binary Linked List)实现
二叉树(Binary Tree)的二叉链表(Binary Linked List)实现