本文次要记录一下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