码迷,mamicode.com
首页 > 其他好文 > 详细

LC.234.Palindrome Linked List

时间:2018-02-24 10:44:40      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:tno   nbsp   eve   开始   ==   tps   problem   span   链表   

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

标签:tno   nbsp   eve   开始   ==   tps   problem   span   链表   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!