234. 回文链表

时间:2024-06-08 13:11:02

 

/**
 * 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.next==null){
            return true;
        }
        Stack<ListNode> stk = new Stack<>();
        ListNode slow = head;
        ListNode fast = head;
        while(fast!=null && fast.next!=null){
            slow = slow.next;
            fast=fast.next.next;
        }
        while(slow!=null){
            stk.push(slow);
            slow = slow.next;
        }
        while(!stk.isEmpty()){
            if(head.val!=stk.pop().val){
                return false;
            }
            head = head.next;
        }
        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) {
        if(head.next==null){
            return true;
        }
        Stack<ListNode> stk = new Stack<>();
        ListNode slow = head;
        ListNode fast = head;
        while(fast.next!=null && fast.next.next!=null){
            slow = slow.next;
            fast=fast.next.next;
        }
        ListNode n2 = slow.next;//right first
        slow.next = null;
        ListNode n1 = null;
        while(n2!=null){
            ListNode temp = n2.next;
            n2.next = n1;
            n1 = n2;
            n2 = temp;
        }
        boolean res = true;
        while(n1!=null && head!=null){
            if(n1.val!=head.val){
                res = false;
                break;
            }
            n1 = n1.next;
            head = head.next;
        }
        return res;
    }
}