day13 leetcode-hot100-24(链表3)

234. 回文链表 - 力扣(LeetCode)

1.转化法

思路

将链表转化为列表进行比较

复习到的知识

arraylist的长度函数:list.size()

具体代码
java 复制代码
/**
 * 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) {
        ListNode n = head;
        List<Integer> list = new ArrayList<>();
        while(n!=null){
            list.add(n.val);
            n=n.next;
        }
        int l=0;
        int r=list.size()-1;
        while(l<r){
            if(list.get(l)!=list.get(r)){
                return false;
            }
            l++;
            r--;
        }
        return true;

    

    }
}

2.反转法

思路

将后半段链表反转,然后进行比较。

知识

取单链表的中间节点:快慢指针

具体代码
java 复制代码
/**
 * 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) {
        ListNode n1 = secondL(head);
        ListNode n2 = reverseL(n1.next);
        ListNode p1 = head;
        ListNode p2 = n2;
        


        while(p2!=null){
            if(p1.val != p2.val){
                return false;
            }

            p1=p1.next;
            p2=p2.next;
        }
        return true;
        
    }

    public ListNode reverseL(ListNode l){
        ListNode old = null;
        ListNode current = l;
        while(current!=null){
            ListNode tem = current.next;
            current.next = old;
            old =current;
            current= tem;
        }
        return old;
    }

    public ListNode secondL(ListNode l){
        ListNode slow = l;
        ListNode fast = l;
        while(fast.next!=null && fast.next.next!=null){
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
}
相关推荐
while(1){yan}2 小时前
数据结构之链表
数据结构·链表
Han.miracle4 小时前
数据结构——二叉树的从前序与中序遍历序列构造二叉树
java·数据结构·学习·算法·leetcode
mit6.8246 小时前
前后缀分解
算法
独自破碎E6 小时前
判断链表是否为回文
数据结构·链表
你好,我叫C小白6 小时前
C语言 循环结构(1)
c语言·开发语言·算法·while·do...while
寂静山林9 小时前
UVa 10228 A Star not a Tree?
算法
Neverfadeaway9 小时前
【C语言】深入理解函数指针数组应用(4)
c语言·开发语言·算法·回调函数·转移表·c语言实现计算器
Madison-No710 小时前
【C++】探秘vector的底层实现
java·c++·算法
Swift社区10 小时前
LeetCode 401 - 二进制手表
算法·leetcode·ssh
派大星爱吃猫10 小时前
顺序表算法题(LeetCode)
算法·leetcode·职场和发展