标签:
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 /** 2 * 本代码由九章算法编辑提供。没有版权欢迎转发。 3 * - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。 4 * - 现有的面试培训课程包括:九章算法班,系统设计班,BAT国内班 5 * - 更多详情请见官方网站:http://www.jiuzhang.com/ 6 */ 7 8 // This code would destroy the original structure of the linked list. 9 // If you do not want to destroy the structure, you can reserve the second part back. 10 public class Solution { 11 /** 12 * @param head a ListNode 13 * @return a boolean 14 */ 15 public boolean isPalindrome(ListNode head) { 16 if (head == null) { 17 return true; 18 } 19 20 ListNode middle = findMiddle(head); 21 middle.next = reverse(middle.next); 22 23 ListNode p1 = head, p2 = middle.next; 24 while (p1 != null && p2 != null && p1.val == p2.val) { 25 p1 = p1.next; 26 p2 = p2.next; 27 } 28 29 return p2 == null; 30 } 31 32 private ListNode findMiddle(ListNode head) { 33 if (head == null) { 34 return null; 35 } 36 ListNode slow = head, fast = head.next; 37 while (fast != null && fast.next != null) { 38 slow = slow.next; 39 fast = fast.next.next; 40 } 41 42 return slow; 43 } 44 45 private ListNode reverse(ListNode head) { 46 ListNode prev = null; 47 48 while (head != null) { 49 ListNode temp = head.next; //为了不让head.next丢失,存tmp 50 head.next = prev; //head指向prev,完成反转 51 prev = head; //操作下一个节点 52 head = temp; //操作下一个节点 53 } 54 55 return prev; 56 } 57 }
标签:
原文地址:http://www.cnblogs.com/hygeia/p/4899812.html