当前位置 博文首页 > Yawn:Leetcode——回文链表

    Yawn:Leetcode——回文链表

    作者:[db:作者] 时间:2021-08-02 18:38

    1. 题目

    请判断一个链表是否为回文链表。

    示例 1:
    输入: 1->2
    输出: false

    示例 2:
    输入: 1->2->2->1
    输出: true

    进阶:
    你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

    2. 题解

    解法一:

    通俗解法:将值复制到数组中后用双指针法

    • 计算出链表长度
    • 把链表中的值都存进数组
    • 判断数组是不是回文串
    /**
     * 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 cur1 = head;
            ListNode cur2 = head;
            int len = 0;
            while(cur1 != null){
                cur1 = cur1.next;
                len++;
            }
            int[] temp = new int[len];
            for(int i = 0; i < len; i++){
                if(cur2 != null){
                    temp[i] = cur2.val;
                    cur2 = cur2.next;
                }
            }
            int left = 0, right = len - 1;
            while(left < right){
                if(temp[left] != temp[right]){
                    return false;
                }
                left++;
                right--;
            }
            return true;
        }
    }
    

    解法二:

    • 先把所有值使用栈存储
    • 相当于链表倒置
    • 逐一对比即可
    /**
     * 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 cur1 = head;
            ListNode cur2 = head;
            Stack<Integer> stack = new Stack<>();
            int n = 0;
            while(cur1 != null){
                cur1 = cur1.next;
                n++;
            }
            for(int i = 0; i < n; i++){
                stack.push(cur2.val);
                cur2 = cur2.next;
            }
            for(int i = 0; i < n; i++){
                if(stack.pop() != head.val)
                    return false;
                head = head.next;
            }
            return true;
        }
    }
    
    cs
    上一篇:没有了
    下一篇:没有了