golang力扣leetcode 234.回文链表

简介: golang力扣leetcode 234.回文链表

题解

思路:取中点分成两个链表,翻转第二个,开始比较,注意其中一个为nil就可以停止了,因为有可能节点为奇数的情况

代码

package main
type ListNode struct {
  Val  int
  Next *ListNode
}
func findMiddle(head *ListNode) *ListNode {
  slow := head
  fast := head.Next
  for fast != nil && fast.Next != nil {
    slow = slow.Next
    fast = fast.Next.Next
  }
  return slow
}
func reverseList(head *ListNode) *ListNode {
  curr := head
  var p *ListNode
  for curr != nil {
    next := curr.Next
    curr.Next = p
    p = curr
    curr = next
  }
  return p
}
func isPalindrome(head *ListNode) bool {
  if head == nil {
    return true
  }
  mid := findMiddle(head)
  tail := reverseList(mid.Next)
  for head != nil && tail != nil {
    if head.Val != tail.Val {
      return false
    }
    head = head.Next
    tail = tail.Next
  }
  return true
}
func main() {
}
目录
相关文章
【移除链表元素】LeetCode第203题讲解
【移除链表元素】LeetCode第203题讲解
|
15天前
【力扣】409.最长回文串
【力扣】409.最长回文串
|
15天前
【力扣】21. 合并两个有序链表
【力扣】21. 合并两个有序链表
|
2月前
|
存储 JavaScript
leetcode82. 删除排序链表中的重复元素 II
leetcode82. 删除排序链表中的重复元素 II
22 0
|
2月前
leetcode83. 删除排序链表中的重复元素
leetcode83. 删除排序链表中的重复元素
10 0
|
2月前
leetcode2807.在链表中插入最大公约数
leetcode2807.在链表中插入最大公约数
16 0
|
2月前
leetcode2487.从链表中移除节点
leetcode2487.从链表中移除节点
20 1
|
2月前
|
存储 算法
LeetCode刷题--- 61. 旋转链表(快慢指针+闭合为环)
LeetCode刷题--- 61. 旋转链表(快慢指针+闭合为环)
|
2月前
|
算法 索引
LeetCode刷题--- 138. 复制带随机指针的链表(哈希表+迭代)
LeetCode刷题--- 138. 复制带随机指针的链表(哈希表+迭代)
|
2月前
|
机器学习/深度学习 算法
力扣刷题日常(一)
力扣刷题日常(一)
20 2

热门文章

最新文章