編寫一個函數,檢查輸入的鏈表是否是迴文的。
示例 1:
輸入: 1->2
輸出: false
示例 2:
輸入: 1->2->2->1
輸出: true
進階:
你能否用 O(n) 時間複雜度和 O(1) 空間複雜度解決此題?
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/palindrome-linked-list-lcci
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
兩個關鍵點:
1.快慢指針找中點;
2.反轉鏈表;
func isPalindrome(head *ListNode) bool {
tail := reverse(middle(head))
for head != nil && tail != nil {
if head.Val != tail.Val {
return false
}
head = head.Next
tail = tail.Next
}
return true
}
// 尋找中間節點
func middle(head *ListNode) *ListNode {
if head == nil {
return nil
}
fast, slow := head, head
for fast != nil && fast.Next != nil {
fast = fast.Next.Next
slow = slow.Next
}
return slow
}
// 反轉鏈表
func reverse(head *ListNode) *ListNode {
if head == nil {
return nil
}
cur := head.Next
head.Next = nil
for cur != nil {
next := cur.Next
cur.Next = head
head = cur
cur = next
}
return head
}