首页 > 其他 > 详细

LC.234.Palindrome Linked List

时间:2018-02-24 10:31:08      阅读:205      评论:0      收藏:0      [点我收藏+]
https://leetcode.com/problems/palindrome-linked-list/description/
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?
time O(n) space:O(1)

(1) 先找中点
(2) 再reverse后半段
(3) 不用管两个子linked list的长度是否相等,从各个子链表的头开始一个一个比较。值不相等就返回false,相等就继续移动。

 1  public boolean isPalindrome(ListNode head) {
 2         if (head == null) return true ;
 3         ListNode fast = head , slow = head ;
 4         ListNode mid = null ;
 5         //step 1: find the middle node: when fast reaches the end, slow reaches the mid
 6         while (fast != null && fast.next != null){
 7             fast = fast.next.next ;
 8             slow = slow.next ;
 9         }
10         mid = slow ;
11         //step 2: reverse the 2nd half
12         ListNode lastHead = reverse(mid) ;
13         //step 3: compare the 1st half with the 2nd half, if not the same return false
14         while (head != null && lastHead != null){
15             if (head.val != lastHead.val) {
16                 return false ;
17             }
18             head = head.next ;
19             lastHead = lastHead.next ;
20         }
21         return true ;
22     }
23 
24     /*1->2->3->4   to 1<-2<-3<-4
25     *                          p c
26     * */
27     private ListNode reverse(ListNode head){
28         ListNode pre = null ;
29         ListNode curr = head ;
30         ListNode next = null ;
31         while (curr!= null){
32             ListNode temp = curr.next ;
33             curr.next = pre ;
34             pre = curr ;
35             curr = temp;
36         }
37         return pre ;
38     }

 

LC.234.Palindrome Linked List

原文:https://www.cnblogs.com/davidnyc/p/8464293.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!