1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | public class Solution { public boolean isPalindrome(ListNode head) { if (head == null) return true; ListNode slow = head; ListNode fast = head; while (fast.next != null && fast.next.next != null){ fast = fast.next.next; slow = slow.next; } ListNode mid = slow; slow = slow.next; ListNode tailHead = reverseList(slow); ListNode fromBack = tailHead; ListNode fromFront = head; boolean result = true; while (result && fromBack != null){ if (fromBack.val == fromFront.val){ fromBack = fromBack.next; fromFront = fromFront.next; }else{ result = false; } } reverseList(tailHead); return result; } ListNode reverseList(ListNode node){ if (node == null || node.next == null) return node; ListNode current = node.next; ListNode previous = node; previous.next = null; while (current != null){ ListNode next = current.next; current.next = previous; previous = current; current = next; } return previous; } } |
Friday, November 13, 2015
[leetcode]Palindrome Linked List
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment