算法的重要性,我就很少說了吧,想去大廠,就必需要通過基礎知識和業務邏輯面試+算法面試。 今天和你們聊的問題叫作 迴文鏈表,咱們先來看題面:https://leetcode-cn.com/problems/palindrome-linked-list/面試
Given the head of a singly linked list, return true if it is a palindrome.算法
請判斷一個鏈表是否爲迴文鏈表。數組
示例 1:
輸入: 1->2
輸出: false
示例 2:
輸入: 1->2->2->1
輸出: true
進階:
你可否用 O(n) 時間複雜度和 O(1) 空間複雜度解決此題?數據結構
https://www.imooc.com/article/289808 ide
首先是尋找鏈表中間節點,這個能夠用快慢指針來解決,快指針速度爲2,慢指針速度爲1,快指針遍歷完鏈表時,慢指針恰好走到中間節點(相對)。而後是判斷是不是迴文鏈表:不考慮進階要求的話,方法千千萬。能夠把前半部分暫存入新的數組、鏈表、哈希表等等數據結構,而後依次倒序取出,與後半部分鏈表每一個節點的值對比便可。更簡單的是直接用數據結構 - 棧,先進後出,把節點壓入棧中,到中間節點後,依次從棧中彈出節點,與後半部分的節點值對比便可。直接思考進階要求,在 O(1) 的空間複雜度下,只能選擇操做原鏈表來完成該題。好在這道題只要求返回布爾值,即使把原鏈表改變了也不用擔憂。咱們能夠將鏈表後半部分 反轉,利用迭代法反轉鏈表,時間複雜度爲 O(n),空間複雜度爲 O(1),因此符合要求。而後從原鏈表頭節點 與 反轉後後半部分鏈表頭節點開始對比值便可。函數
class Solution { public boolean isPalindrome(ListNode head) { ListNode fast = head; ListNode slow = head; if (fast == null || fast.next == null) return true; while (fast.next != null && fast.next.next != null) { fast = fast.next.next; slow = slow.next; } ListNode newHead = reverseList(slow.next); while (newHead != null) { if (head.val != newHead.val) return false; head = head.next; newHead = newHead.next; } return true; } //反轉鏈表函數--詳情請看前文 private ListNode reverseList(ListNode head) { if (head.next == null) return head; ListNode pre = null; ListNode tmp; while (head!= null) { tmp = head.next;//tmp暫存當前節點的下一個節點 head.next = pre;//當前節點下一個指向pre pre = head;//刷新pre head = tmp;//刷新當前節點爲tmp } return pre; } }