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

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 the head
     * @return bool布尔型
     */
    public boolean isPail (ListNode head) {
        // write code here
        if (head == null || head.next == null) {
            return true;
        }
        Stack<Integer> p = new Stack<>();
        ListNode cur = head;
        while(cur != null) {
            p.push(cur.val);
            cur = cur.next;
        }
        ListNode cur2 = head;
        while(!p.isEmpty()) {
            int g = p.pop();
            int val = cur2.val;
            if (g != val) {
                return false;
            }
            cur2 = cur2.next;
        }
        return true;
    }

    public ListNode reverseListNode(ListNode reverseNode) {
        //O(1)的反转链表
        if (reverseNode == null) {
            return reverseNode;
        }
        ListNode current = reverseNode;
        ListNode prev = null;
        while(current != null) {
            ListNode tmp = current.next;
            current.next = prev;
            prev = current;
            current = tmp;
        }
        return prev;
    }
}

思路,反转链表, 然后遍历,如果相等则返回true,但是反转链表在这个ide里会改变原来的值

因此用堆栈先遍历并存储链表的值,然后判断值是否相等即可。

全部评论

相关推荐

饿魔:看到在线简历了吧
点赞 评论 收藏
分享
牛客41406533...:回答他在课上学,一辈子待在学校的老教授用三十年前的祖传PPT一字一句的讲解,使用谭浩强红皮书作为教材在devc++里面敲出a+++++a的瞬间爆出114514个编译错误来学这样才显得专业
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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