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:
- Assign the intersection combination of two linked lists to linked list a
- 206. Reverse Linked List [easy] (Python)
- 【Hackerrank】Reverse a doubly linked list
- The sum of the two numbers of leetcode
- JMeter linked database
- LeetCode 23. Merge k Sorted Lists(java)
- Leetcode 832. Flip image
- Common causes of Leetcode Runtime Error
- LeetCode 332. Reconstruct Itinerary
- Leetcode: 7. Reverse Integer(JAVA)
- Leetcode 34 finds the first and last position of an element in the sorted array (medium)
- Leetcode solution 189 Rotate Array Java version
- Golang gets the list of files under the folder
- Common attributes and methods of list and map in Dar
- Determine whether the list is empty isempty
- Conversion between list and string array
- 【Bug-python】IndexError: list index out of range
- Pre initialization of list content and length in Python
- Mybatis custom list collection parser
- Struts 2 encapsulates form data into list and map sets