using reversing a list


  • 0
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public boolean isPalindrome(ListNode head) {
            if(head == null || head.next == null)
                return true;
            ListNode mark = new ListNode(0);
            mark.next = head;
            int n = 0;
            while(head != null){
                n ++;
                head = head.next;
            }
            head = mark.next;
            ListNode pre = null;
            for(int i = 0; i < n / 2; i++){
                ListNode temp = head.next;
                head.next = pre;
                pre = head;
                head = temp;
            }
            if(n % 2 == 1)
                head = head.next;
            while(head != null && pre != null){
                if(head.val != pre.val)
                    return false;
                else{
                    head = head.next;
                    pre = pre.next;
                }
            }
            return true;
            
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.