算法 | Leetcode 面试题 02.06. 回文链表

编写一个函数,检查输入的链表是否是回文的。

示例 1:

输入: 1->2
输出: false

示例 2:

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

进阶:

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

题解:
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
        // List<Integer> nodes = new ArrayList<>();
        // ListNode node = head;
        // while(node!= null){
        //     nodes.add(node.val);
        //     node = node.next;
        // }
        // int size = nodes.size();
        // int r = size/2;
        // for(int i=0;i<r;i++){
        //     int left = nodes.get(i);
        //     int right = nodes.get(size-i-1);
        //     if(left!=right){
        //         return false;
        //     }
        // }
        // return true;
        //快慢节点
        ListNode slow = head;
        ListNode fast = head;
        while(fast!=null&&fast.next!=null){
            slow = slow.next;
            fast = fast.next.next;
        }
        //反转后半部分
        ListNode pre = null;
        while(slow != null){
            ListNode next = slow.next;
            slow.next = pre;
            pre = slow;
            slow = next;
        }
        //前后两段比较是否一致
        ListNode node = head;
        while(pre != null){
            if(pre.val != node.val){
                return false;
            }
            pre = pre.next;
            node = node.next;
        }
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/CYK5201995/article/details/106408592
今日推荐