Topic describes
Determine whether a linked list is a palindrome list.
// 1 2 nil
// 1 2 1 nil
// 1 2 2 1 nil
Thought analysis
The fast and slow pointer finds the midpoint of the linked list and splits the midpoint and reverses the tail list to compare whether the values of the head and tail list are equal in turn
Code implementation
func isPalindrome(head *ListNode) bool {
if head == nil {
return true
}
fast := head.Next
slow := head
for fast != nil && fast.Next != nil {
fast = fast.Next.Next
slow = slow.Next
}
tail := reverse(slow.Next)
slow.Next = nil
for head != nil && tail != nil {
if head.Val != tail.Val {
return false
}
head = head.Next
tail = tail.Next
}
return true
}
func reverse(head *ListNode) *ListNode {
if head == nil {
return head
}
var pre *ListNode
for head != nil {
temp := head.Next
head.Next = pre
pre = head
head = temp
}
return pre
}
Read More:
- 206. Reverse Linked List [easy] (Python)
- The sum of the two numbers of leetcode
- 21. Merge Two Sorted Lists [easy] (Python)
- 【Hackerrank】Reverse a doubly linked list
- 1143 Lowest Common Ancestor
- 7. Reverse Integer [easy] (Python)
- Analysis of compilation errors of “error conflicting types for function”
- About java “Error: bad binary operator types”
- IntegrityError at ** NOT NULL constraint failed: learning_logs_topic.owner_id
- Dataframe groupby custom aggregate function
- Leetcode 832. Flip image
- How to get all the keys of map by golang
- Haskell learning — Grammar
- The 11th Zhejiang Provincial Collegiate Programming Contest
- C++ —Return multiple values of different types
- Reverse function: reverses container contents
- Typeerror in Python: ‘nonetype’ object is not Iterable
- The reason why HashMap multithreads send out life and death loops
- Reading and saving opencv Python video
- panic: runtime error: index out of range