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 }
原文地址:https://www.cnblogs.com/davidnyc/p/8464293.html
时间: 2024-10-09 00:58:35