判断链表是否为回文

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

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
        if(head==null){
            return true;
        }
        Stack<ListNode> stack=new Stack<>();
        ListNode index=head;
        while(index!=null){
            stack.add(index);
            index=index.next;
        }
        index=head;
        while(index!=null){
            if(index.val!=stack.pop().val){
                return false;
            }
            index=index.next;
        }
        return true;
    }
}
全部评论
内存占用较大
点赞 回复 分享
发布于 2021-03-30 22:49

相关推荐

评论
12
收藏
分享

创作者周榜

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