判断一个链表是否为回文结构
判断一个链表是否为回文结构
http://www.nowcoder.com/questionTerminal/3fed228444e740c8be66232ce8b87c2f
解题思路:回文结构的链表元素个数为偶数,因此先求出链表节点个数。为偶数时,用栈来存储前半部分节点的值,然后与后半部分节点中的值依次比较。
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
Stack<Integer> s=new Stack<>();
ListNode H=head;
int num=0;
while(head!=null){
num++;
head=head.next;
}
if(num%2==0){
head=H;
for(int i=0;i<num/2;i++){
s.push(head.val);
head=head.next;
}
for(int i=0;i<num/2;i++){
if(head.val==s.peek()){
s.pop();
head=head.next;
}
else{
return false;
}
}
return true;
}
return false;
}
}
