234. 回文链表

送分小仙女□ 提交于 2020-02-22 18:56:27
判断一个链表是否为回文链表。
该题目来自力扣题库

示例

示例 1:
输入: 1->2
输出: false

示例 2:
输入: 1->2->2->1
输出: true

思路

使用栈结构,把当前链表全部压入堆栈。之后再按顺序比较链表节点以及出栈节点是否相同

代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
        if(head==null||head.next==null){
            return true;
        }
        Stack<ListNode> stack=new Stack<ListNode>();
        ListNode cur=head;
        while(cur!=null){
            stack.push(cur);
            cur=cur.next;
        }
        cur=head;
        while(stack.size()>0){
            ListNode prev=stack.pop();
            if(cur.val!=prev.val){
                return false;
            }
            cur=cur.next;
        }
        return true;
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!