From fb982fa79d643bb3e01960bb01897322cc424bf7 Mon Sep 17 00:00:00 2001 From: xiaojun <13589818805@163.com> Date: Sat, 16 Jul 2022 15:00:22 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88234.=E5=9B=9E?= =?UTF-8?q?=E6=96=87=E9=93=BE=E8=A1=A8=EF=BC=89=E7=9A=84go=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0234.回文链表.md | 68 +++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/problems/0234.回文链表.md b/problems/0234.回文链表.md index eeee6fa5..1ac8756a 100644 --- a/problems/0234.回文链表.md +++ b/problems/0234.回文链表.md @@ -276,7 +276,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