234. Palindrome Linked List

来源:互联网 发布:java并发编程 编辑:程序博客网 时间:2024/06/10 11:52

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.

/** * 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.next;while (fast != null) {slow = slow.next;if (fast.next == null)break;fast = fast.next.next;}slow = reverse(slow);while (slow != null) {if (head.val != slow.val)return false;head = head.next;slow = slow.next;}return true;    }    private ListNode reverse(ListNode head) {if (head == null || head.next == null)return head;ListNode temp = reverse(head.next);head.next.next = head;head.next = null;return temp;}}


0 0
原创粉丝点击