234. 回文链表


234. 回文链表

难度简单 872

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

示例 1:

输入: 1->2

输出: false

示例 2:

输入: 1->2->2->1

输出: true

进阶:

你能否用  O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
        List<Integer> vals = new ArrayList<Integer>();

        // 将链表的值复制到数组中
        ListNode currentNode = head;
        while (currentNode != null) &#123;
            vals.add(currentNode.val);
            currentNode = currentNode.next;
        &#125;

        // 使用双指针判断是否回文
        int front = 0;
        int back = vals.size() - 1;
        while (front < back) &#123;
            if (!vals.get(front).equals(vals.get(back))) &#123;
                return false;
            &#125;
            front++;
            back--;
        &#125;
        return true;
    &#125;

// 作者:LeetCode-Solution
// 链接:https://leetcode-cn.com/problems/palindrome-linked-list/solution/hui-wen-lian-biao-by-leetcode-solution/

&#125;

/**
 * Definition for singly-linked list.
 * public class ListNode &#123;
 *     int val;
 *     ListNode next;
 *     ListNode() &#123;&#125;
 *     ListNode(int val) &#123; this.val = val; &#125;
 *     ListNode(int val, ListNode next) &#123; this.val = val; this.next = next; &#125;
 * &#125;
 */
class Solution &#123;
    public boolean isPalindrome(ListNode head) &#123;
        Stack<Integer> stk =new Stack();
        if (null==head || null==head.next) return true;
        ListNode p = head;

        while (p != null) &#123;
            stk.push(p.val);
            p = p.next;
        &#125;
        while (head != null)&#123;
            if(head.val == stk.peek()) &#123;
                stk.pop();
            &#125; else return false;
            head = head.next;
        &#125;
        return true;
    &#125;

// 作者:wo-yao-chu-qu-luan-shuo
// 链接:https://leetcode-cn.com/problems/palindrome-linked-list/solution/hui-wen-lian-biao-fu-zhu-zhan-by-wo-yao-ab2uc/

&#125;

文章作者:   future
版权声明:   本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 future !
 上一篇
141. 环形链表 141. 环形链表
categories: [Blog,Algorithm] 141. 环形链表 public boolean hasCycle(ListNode head) &#123; ListNode fast=head,s
2021-03-02 future
下一篇 
剑指 Offer 58 - II. 左旋转字符串 剑指 Offer 58 - II. 左旋转字符串
剑指 Offer 58 - II. 左旋转字符串难度简单 85 字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串”abcdefg”和数字 2,该函数将返回左旋转两位得
  目录