LeetCode:Palindrome Linked List
1393 ワード
Palindrome Linked List
Total Accepted: 28267
Total Submissions: 113712
Difficulty: Easy
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?
Subscribe to see which companies asked this question
考え方:
1.「速い」ポインタと「遅い」ポインタで、同時に後ろに移動します.2つのポインタの後方移動速度は、fast=2*slow、すなわちslowが1歩、fastが2歩です.
2.slowポインタの最終位置チェーンテーブルの中間位置.
3.前半のチェーンテーブルを逆さにします.
4.2つの部分を比較します.
code:
Total Accepted: 28267
Total Submissions: 113712
Difficulty: Easy
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?
Subscribe to see which companies asked this question
考え方:
1.「速い」ポインタと「遅い」ポインタで、同時に後ろに移動します.2つのポインタの後方移動速度は、fast=2*slow、すなわちslowが1歩、fastが2歩です.
2.slowポインタの最終位置チェーンテーブルの中間位置.
3.前半のチェーンテーブルを逆さにします.
4.2つの部分を比較します.
code:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null) {
return true;
}
ListNode slow = head;
ListNode fast = head;
ListNode p = slow.next;
ListNode pre = slow;
//find mid pointer, and reverse head half part
while(fast.next != null &&fast.next.next != null) {
fast = fast.next.next;
pre = slow;
slow = p;
p = p.next;
slow.next = pre;
}
//odd number of elements, need left move slow one step
if(fast.next == null) slow = slow.next;
slow = slow.next;
p = p.next;
}
return true;
}
}