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;
    }
}
相关推荐
superman超哥1 小时前
仓颉语言中基本数据类型的深度剖析与工程实践
c语言·开发语言·python·算法·仓颉
Learner__Q1 小时前
每天五分钟:滑动窗口-LeetCode高频题解析_day3
python·算法·leetcode
阿昭L2 小时前
leetcode链表相交
算法·leetcode·链表
闻缺陷则喜何志丹2 小时前
【计算几何】仿射变换与齐次矩阵
c++·数学·算法·矩阵·计算几何
liuyao_xianhui2 小时前
0~n-1中缺失的数字_优选算法(二分查找)
算法
hmbbcsm2 小时前
python做题小记(八)
开发语言·c++·算法
机器学习之心3 小时前
基于Stacking集成学习算法的数据回归预测(4种基学习器PLS、SVM、BP、RF,元学习器LSBoost)MATLAB代码
算法·回归·集成学习·stacking集成学习
图像生成小菜鸟3 小时前
Score Based diffusion model 数学推导
算法·机器学习·概率论
声声codeGrandMaster3 小时前
AI之模型提升
人工智能·pytorch·python·算法·ai
黄金小码农3 小时前
工具坐标系
算法