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?

解题报告: 1. 找到LinkedList 的中点 2. 翻转链表(从中点的下一个节点到链表终点)得到另一个链表 3. 依次比较两个节点的值是否相等。

 

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public boolean isPalindrome(ListNode head) {
11         if (head == null || head.next == null) {
12             return true;
13         }
14         ListNode mid = findMid(head);
15         ListNode head_2 = reverse(mid.next);
16         mid.next = null;
17         while (head != null && head_2 != null) {
18             if (head.val != head_2.val) {
19                 return false;
20             }
21             head = head.next;
22             head_2 = head_2.next;
23         }
24         return true;
25     }
26     
27     private ListNode findMid(ListNode head) {
28         ListNode dummy = new ListNode(0);
29         dummy.next = head;
30         ListNode slow = dummy;
31         ListNode fast = dummy.next;
32         while (fast != null && fast.next != null) {
33             fast = fast.next.next;
34             slow = slow.next;
35         }
36         return slow;
37     }
38     
39     private ListNode reverse(ListNode head) {
40         ListNode preNode = null;
41         while (head != null) {
42             ListNode temp = head.next;
43             head.next = preNode;
44             preNode = head;
45             head = temp;
46         }
47         return preNode;
48     }
49 }

 

posted @ 2016-08-13 10:17  YuriFLAG  阅读(120)  评论(0)    收藏  举报