简体   繁体   中英

Is a Singly Linked List Palindrome? JAVA

It is the 234th question on LeetCode. The requirement for this task is to do it in O(n) time and O(1) space. Definition for singly-linked list:

public class ListNode {
  int val;
  ListNode next;
  ListNode(int x) { val = x; }

}

If I write the function like this:

public class Solution {
public boolean isPalindrome(ListNode head) {
    List<Integer> a = new ArrayList<>();
    while(head!=null){
        a.add(head.val);
        head = head.next;
    }
    for(int i=0, j=a.size()-1-i; i<j;){
        if(a.get(i) != a.get(j)){
            return false;
        }
        i++;
        j--;
    }
    return true;
}

}

This will return false if I try [128, 128], but it will return true if I try [127, 127]. I really do not know why. Could anybody help me?

You're decrementing your loop counter but comparing it to your position counter. In other words, while i<j will only go through half the list.

so,

for( int i=0, j=a.size()-1; i<j ; ++i,--j ) {
    if ( a.get(i) != a.get(j) ) return false;
}
return true;

or, a little more obfuscated.

int i=0, j=a.size()-1;
while ( j > i && s[i] == s[j] ) { ++i; --j; }
return j<=i;    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM