首页 > 代码库 > Leetcode 234. Palindrome Linked List

Leetcode 234. Palindrome Linked List

Given a singly linked list, determine if it is a palindrome.

Follow up:
Could you do it in O(n) time and O(1) space?

 

Similar Questions 

Palindrome Number Valid Palindrome Reverse Linked List 

Next challenges
Valid Palindrome Reverse Linked List

 

 

思路:3步走。

1.设置fast和slow指针,使得fast遍历列表后,slow位于列表中偏右部。

2.反转slow侧的列表。

3.将fast指向head,依次比较slow侧的列表和fast侧列表每个元素的值。

 

代码:上述1和2的2个操作还是比较经典的。

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public boolean isPalindrome(ListNode head) {
11         ListNode fast = head, slow = head;
12 //        每1次fast都比slow多走1个单位直到fast不能再1次走2步为止
13         while(fast != null && fast.next != null) {
14             slow = slow.next;
15             fast = fast.next.next;
16         }
17         if(fast != null) {//有奇数个node,设置slow侧的node数量少于fast侧的node数量
18             slow = slow.next;
19         }
20         slow = reverse(slow);//slow侧列表反转
21         fast = head;
22         while(slow != null && slow.val == fast.val) {
23             slow = slow.next;
24             fast = fast.next;
25         }
26         return slow == null;
27     }
28     
29     //列表反转
30     public ListNode reverse(ListNode head) {
31         ListNode prev = null;
32         while(head != null) {
33             ListNode next = head.next;
34             head.next = prev;
35             prev = head;
36             head = next;
37         }
38         return prev;
39     }
40 }

 

Leetcode 234. Palindrome Linked List