题解 | #字符串出现次数的TopK问题#

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

http://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f

public class NC96 {
    /**
     *
     * @param head ListNode类 the head
     * @return bool布尔型
     */
    public boolean isPail (NC66.ListNode head) {
        // write code here
        int n = 0;
        NC66.ListNode tempNode = head;
        while (tempNode != null){
            n++;
            tempNode = tempNode.next;
        }
             // 先遍历链表获取链表的长度

        if (n == 1){
            return true;
            //      若长度为1 直接返回true
        }else {
            Stack<Integer> stack = new Stack<>();
            if (n % 2 == 0){
                        //    长度为偶数时
                NC66.ListNode temp1 = head;
                for (int i = 1; i <= n / 2 ; i++) {
                    stack.push(temp1.val);
                    temp1 = temp1.next;
                }
                while (temp1 != null && ){
                    if (stack.pop() != temp1.val){
                        return false;
                    }
                    temp1 = temp1.next;
                }
                return true;
            }else {
                        //    长度为奇数时
                NC66.ListNode temp1 = head;
                for (int i = 1; i <= n / 2 ; i++) {
                    stack.push(temp1.val);
                    temp1 = temp1.next;
                }
                temp1 = temp1.next;
                while (temp1 != null){
                    if (stack.pop() != temp1.val){
                        return false;
                    }
                    temp1 = temp1.next;
                }
                return true;
            }
        }
    }
}

全部评论

相关推荐

03-27 01:58
已编辑
西北工业大学 Java
在平静中度过当下:如果这个bg也简历挂的话可能他们现在不缺人了吧,我也是这两天投的,阿里和快手投的岗都是简历秒挂
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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