关于leetcode:leetcode链表之回文链表

本文次要记录一下leetcode链表之回文链表

题目

请判断一个链表是否为回文链表。

示例 1:

输出: 1->2
输入: false

示例 2:

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

进阶:
你是否用 O(n) 工夫复杂度和 O(1) 空间复杂度解决此题?

起源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-linked-list
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。

题解

/**
 * 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) {
            return true;
        }
        Stack stack = new Stack();
        ListNode cursor = head;
        while(cursor != null) {
            stack.push(cursor.val);
            cursor = cursor.next;
        }

        cursor = head;
        while(cursor != null) {
            int val = (int)stack.pop();
            if (val != cursor.val) {
                return false;
            }
            cursor = cursor.next;
        }
        return true;
    }
}

小结

这里应用Stack来解决,先遍历一遍放到Stack中,之后再次遍历,挨个跟stack.pop进去的比拟

doc

  • palindrome-linked-list

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理