Merge pull request #1524 from jujunwang/master

添加(234.回文链表)的go版本
This commit is contained in:
程序员Carl
2022-07-28 09:50:34 +08:00
committed by GitHub

View File

@ -258,7 +258,75 @@ class Solution:
### Go
```go
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
//方法一,使用数组
func isPalindrome(head *ListNode) bool{
//计算切片长度,避免切片频繁扩容
cur,ln:=head,0
for cur!=nil{
ln++
cur=cur.Next
}
nums:=make([]int,ln)
index:=0
for head!=nil{
nums[index]=head.Val
index++
head=head.Next
}
//比较回文切片
for i,j:=0,ln-1;i<=j;i,j=i+1,j-1{
if nums[i]!=nums[j]{return false}
}
return true
}
// 方法二,快慢指针
func isPalindrome(head *ListNode) bool {
if head==nil&&head.Next==nil{return true}
//慢指针,找到链表中间分位置,作为分割
slow:=head
fast:=head
//记录慢指针的前一个节点,用来分割链表
pre:=head
for fast!=nil && fast.Next!=nil{
pre=slow
slow=slow.Next
fast=fast.Next.Next
}
//分割链表
pre.Next=nil
//前半部分
cur1:=head
//反转后半部分总链表长度如果是奇数cur2比cur1多一个节点
cur2:=ReverseList(slow)
//开始两个链表的比较
for cur1!=nil{
if cur1.Val!=cur2.Val{return false}
cur1=cur1.Next
cur2=cur2.Next
}
return true
}
//反转链表
func ReverseList(head *ListNode) *ListNode{
var pre *ListNode
cur:=head
for cur!=nil{
tmp:=cur.Next
cur.Next=pre
pre=cur
cur=tmp
}
return pre
}
```
### JavaScript