commit 64c805cf0675e1b4a6c0a7033f1242c4e26be990 Author: li_chx Date: Tue Mar 10 21:48:16 2026 +0800 234. 回文链表 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a09c56d --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/.idea diff --git a/main.go b/main.go new file mode 100644 index 0000000..fb9509f --- /dev/null +++ b/main.go @@ -0,0 +1,55 @@ +package main + +import "fmt" + +// ListNode Definition for singly-linked list. +type ListNode struct { + Val int + Next *ListNode +} + +func isPalindrome(head *ListNode) bool { + srcHead := head + head = head.Next + // var left, right *ListNode + cnt := 1 + for head != nil { + head = head.Next + cnt++ + } + head = srcHead.Next + lastNode := srcHead + srcHead.Next = nil + half := cnt / 2 + half-- + for range half { + p := head.Next + head.Next = lastNode + lastNode = head + head = p + } + if cnt&1 == 1 { + head = head.Next + } + for head != nil && lastNode != nil { + if head.Val != lastNode.Val { + return false + } + head = head.Next + lastNode = lastNode.Next + } + if head != nil || lastNode != nil { + return false + } + return true +} + +func main() { + isPalindrome := isPalindrome(&ListNode{ + Val: 1, + Next: &ListNode{ + Val: 2, + }, + }) + fmt.Printf("isPalindrome: %v\n", isPalindrome) +}