234. Palindrome Linked List

题目:

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/

2/28/2017

参考别人的答案,因为一开始不知道可不可以改变list的结构。

 1 public class Solution {
 2     public boolean isPalindrome(ListNode head) {
 3         if (head == null || head.next == null) return true;
 4         ListNode mid = findMidNode(head);
 5         ListNode ret = reverseList(mid);
 6 
 7         while(ret != null) {
 8             if (head.val != ret.val) return false;
 9             head = head.next;
10             ret = ret.next;
11         }
12         return true;
13     }
14     private ListNode findMidNode(ListNode head) {
15         ListNode slow = head;
16         ListNode fast = head;
17 
18         while (fast != null) {
19             fast = fast.next;
20             if (fast != null) {
21                 fast = fast.next;
22                 slow = slow.next;
23             }
24         }
25         return slow;
26     }
27     private ListNode reverseList(ListNode head) {
28         ListNode dummy = new ListNode(0);
29         ListNode tmp;
30         while (head != null) {
31             tmp = head.next;
32             head.next = dummy.next;
33             dummy.next = head;
34             head = tmp;
35         }
36         return dummy.next;
37     }
38 }

 

posted @ 2017-03-01 06:01  panini  阅读(152)  评论(0编辑  收藏  举报