基於BIM ifc標準的施工過程模擬軟體測試日誌
阿新 • • 發佈:2021-06-20
234. 迴文連結串列
請判斷一個連結串列是否為迴文連結串列。
示例 1:
輸入: 1->2 輸出: false
示例 2:
輸入: 1->2->2->1 輸出: true
進階:
你能否用O(n) 時間複雜度和 O(1) 空間複雜度解決此題?
ref:https://leetcode-cn.com/problems/palindrome-linked-list/solution/234-hui-wen-lian-biao-by-qquser-2-8dd8/
-思路1:遞迴 思考:首尾進行比較,怎麼使用遞迴獲得連結串列的最後一個節點。 1.首先遞迴走到連結串列最後節點 2.與前頭元素比較 1)若相等,繼續 2)若不等,則returnfalse 注意具體實現:
class Solution { private ListNode front; public boolean isPalindrome(ListNode head) { front = head; return reverse(head); } private boolean reverse(ListNode head) { if (head != null) {-思路2:快慢指標的形式,將連結串列分為前後兩個部分,fast走兩步,slow走一步。最終slow到達的位置時前半部分的最後一個元素 注意:`findFirstEnd方法`最終slow到達的是連結串列的奇數長度中間節點或者偶數長度除以2的位置 如: ``` 12345到達val=3處 1234到達val=2處 ```if (!reverse(head.next)) return false; if (head.val != front.val) return false; front = front.next; } return true; } }
具體程式碼:
classSolution { public boolean isPalindrome(ListNode head) { ListNode firstEnd = findFirstEnd(head); ListNode secondEnd = reverseList(firstEnd.next); boolean flag = true; ListNode first = head; ListNode second = secondEnd; while (first != null && second != null) { if (first.val != second.val) { flag = false; break ; } first = first.next; second = second.next; } firstEnd.next = reverseList(secondEnd); return flag; } private ListNode findFirstEnd(ListNode head) { ListNode slow = head; ListNode fast = head; while (fast.next != null && fast.next.next != null) { fast = fast.next.next; slow = slow.next; } return slow; } private ListNode reverseList(ListNode head) { ListNode pre = null; ListNode cur = head; while (cur != null) { ListNode t = cur.next; cur.next = pre; pre = cur; cur = t; } return pre; } }