题解 | #判断一个链表是否为回文结构#

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

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

import java.util.Stack;

/*
 * 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 (null == head) {
            return false;
        }
        if (null == head.next) {
            return true;
        }
        // 具体代码实现
        // 定义一个辅助栈
        Stack<Integer> stack = new Stack<>();
        // 定义一个辅助指针
        ListNode tp = head;
        // 将链表内的所有节点依次入栈
        while (null != tp) {
            stack.push(tp.val);
            tp = tp.next;
        }
        tp = head;
        // 定义一个临时变量,用于存放从栈中弹出的数字
        int val = 0;
        // 将栈中的节点依次弹出,并与原链表的节点依次比较
        while (!stack.isEmpty()) {
            val = stack.pop();
            if (val != tp.val) {
                return false;
            }
            tp = tp.next;
        }
        return true;
    }
}
全部评论

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务