回味链表、字符串、数组

回文链表
在这里插入图片描述
第一步找到中心节点。使用的方法是快慢指针的方法。需要把节点分为奇数和偶数。

最开始的判断

 if(head == null || head.next == null){
            return true;
        }

定义指针
fast为快指针,slow为慢指针,pre为slow前面的指针,作用是用来隔绝中间节点

//定义快慢指针
ListNode fast = head , slow = head ,pre = null;
while(fast !=null && fast.next != null){
            fast = fast.next.next;
            pre = slow;
            slow = slow.next;

        }

第二步,需要分奇偶来判断
1-2-3-3-2-1
当节点为偶数的时候,那么slow为第二个3,pre为第一个3,pre.next= null就是将前半部分和后半部分隔开。
当节点为奇数的时候,1-2-3-2-1。slow指向的是3,pre指向的是2,那么我们需要将3给孤立起来,只用反转2-1然后再比较。

if(fast == null){
            // odd numbers of nodes 
            pre.next = null;
            slow = reverse(slow);
            while(head != null){
                if(head.val != slow.val)  return false;
                head = head.next;
                slow = slow.next;
            }
             return true;

        }else{
            //奇数个
            pre.next = null;
            ListNode next = slow.next;
            slow.next = null;
            next = reverse(next);
            while(head != null){
                if(head.val != next.val) return false;
                head = head.next;
                next = next.next;
            }
            return true;
        }

第三步:写出反转函数
1-2-3进行反转。
首先定义一个空节点,让pre<- head 往后移动。知道head==null就停止。最后返回3-2-1。反转成功。

public ListNode reverse(ListNode head){
            ListNode pre = null;
            while(head != null){
                ListNode next = head.next;  // 1-2-3 中的2
                  head.next = pre;
                  pre = head;
                  head = next;
            }
            return pre;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值