判断一个链表是否为回文结构

判断一个链表是否为回文结构

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;
    }
}
全部评论
回文串字符个数不一定是偶数吧
点赞 回复 分享
发布于 2020-11-02 23:21

相关推荐

07-02 10:44
门头沟学院 C++
码农索隆:太实诚了,告诉hr,你能实习至少6个月
点赞 评论 收藏
分享
但听说转正率很低,我现在有在实习了,好纠结要不要去
熬夜脱发码农:转正率低归低,但是实习的经历你可以拿着,又不是说秋招不准备了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务