标签:eterm you output 一个 实现 and lse def inpu
Given a singly linked list, determine if it is a palindrome.
Input: 1->2
Output: false
Example 2:
Input: 1->2->2->1
Output: true
Follow up:
Could you do it in O(n) time and O(1) space?
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null)
return true;
ListNode fast = head;
ListNode slow = head;
while(fast!=null&&fast.next!=null){
fast = fast.next.next;
slow = slow.next;
}
if(fast != null)
slow = slow.next;
slow = reverse(slow);
fast = head;
while(slow!=null){
if(head.val != slow.val){
return false;
}
head= head.next;
slow = slow.next;
}
return true;
}
ListNode reverse(ListNode head){
ListNode prev = null;
while(head!=null){
ListNode tmp = head.next;
head.next = prev;
prev = head;
head = tmp;
}
return prev;
}
}
Valid Palindrome Easy
Reverse Linked List Easy
leetcode 234. Palindrome Linked List
标签:eterm you output 一个 实现 and lse def inpu
原文地址:https://www.cnblogs.com/clnsx/p/12303355.html