题目:
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?
链接: http://leetcode.com/problems/palindrome-linked-list/
题解:
判断链表是否是Palindrome。 我们分三步解,先用快慢指针找中点,接下来reverse中点及中点后部,最后逐节点对比值。
Time Complexity - O(n), Space Complexity - O(1)
/** * 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 || head.next == null) return true; ListNode mid = findMid(head); ListNode tail = reverse(mid); mid.next = null; while(head != null && tail != null) { if(head.val != tail.val) return false; else { head = head.next; tail = tail.next; } } return true; } private ListNode findMid(ListNode head) { // find mid node of list if(head == null || head.next == null) return head; ListNode slow = head, fast = head; while(fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; } return slow; } private ListNode reverse(ListNode head) { // reverse listnode if(head == null || head.next == null) return head; ListNode dummy = new ListNode(-1); while(head != null) { ListNode tmp = head.next; head.next = dummy.next; dummy.next = head; head = tmp; } return dummy.next; } }
Reference
原文:http://www.cnblogs.com/yrbbest/p/5002340.html