NC96 判断一个链表是否为回文结构
描述
给定一个链表,请判断该链表是否为回文结构。
示例1
输入:
[1]
复制
返回值:
true
复制
示例2
输入:
[2,1]
复制
返回值:
false
复制
说明:
2->1
示例3
输入:
[1,2,2,1]
复制
返回值:
true
复制
说明:
1->2->2->1
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类 the head
* @return bool布尔型
*/
public boolean isPail (ListNode head) {
// write code here
if(head == null){
return false ;
}
if(head.next == null){
return true ;
}
List<Integer> list = new ArrayList<Integer>();
while(head != null){
list.add(head.val) ;
head = head.next ;
}
for(int i = 0 , j = list.size() -1 ; i < j ; i++ , j--){
if(!list.get(i).equals(list.get(j)) ){
return false ;
}
}
return true ;
}
}