234. 回文链表

234. 回文链表

思路:快慢指针,找到中间的节点,然后将中间节点后面的(slow.next)全部reverse,然后依次比较。

注意,reverse的是slow.next后面的。

AC code。

javascript 复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
        if(head == null || head.next==null) return true;
     //   ListNode dummy = new ListNode();
       // dummy.next = head;
     //   head = dummy;
        ListNode fast=head, slow=head, slowpre = head;

        while(fast.next!=null && fast.next.next!=null){
            System.out.println("执行快慢指针时slow=" + slow.val  );
            fast = fast.next.next;
            slowpre = slow;
            slow = slow.next;
        }
        System.out.println("执行快慢指针后slow=" + slow.val );

        ListNode half = reverse(slow.next); // 这里需要是slow.next 
        slow = head;
        while(half!=null){
            //System.out.println("half=" + half.val + " slow="+slow.val);
            if(half.val != slow.val)
                return false;
            half = half.next;
            slow = slow.next;
        }
        return true;
    }
    public ListNode reverse(ListNode head){
        ListNode dummy = new ListNode();
        ListNode p = head, r=null;
        while(p!=null){
            r = p.next;
            p.next = dummy.next;
            dummy.next = p;
            p = r;
        }
        return dummy.next;
    }
}
相关推荐
JeffersonZU1 小时前
【数据结构】2-3-1单链表的定义
数据结构·链表
JeffersonZU1 小时前
【数据结构】1-4算法的空间复杂度
c语言·数据结构·算法
L_cl2 小时前
【Python 算法零基础 4.排序 ① 选择排序】
数据结构·算法·排序算法
无聊的小坏坏2 小时前
【数据结构】二叉搜索树
数据结构
丁一郎学编程5 小时前
优先级队列(堆)
java·数据结构
Codeking__5 小时前
前缀和——中心数组下标
数据结构·算法
GG不是gg6 小时前
数据结构:二叉树一文详解
数据结构·青少年编程
花火QWQ6 小时前
图论模板(部分)
c语言·数据结构·c++·算法·图论
姬公子5217 小时前
leetcodehot100刷题——排序算法总结
数据结构·c++·算法·排序算法
Ronin3058 小时前
【C++】18.二叉搜索树
开发语言·数据结构·c++