categories: [Blog,Algorithm]
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) {vals.add(currentNode.val);currentNode = currentNode.next;}// 使用双指针判断是否回文int front = 0;int back = vals.size() - 1;while (front < back) {if (!vals.get(front).equals(vals.get(back))) {return false;}front++;back--;}return true;}// 作者:LeetCode-Solution// 链接:https://leetcode-cn.com/problems/palindrome-linked-list/solution/hui-wen-lian-biao-by-leetcode-solution/}
栈
/*** 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) {Stack<Integer> stk =new Stack();if (null==head || null==head.next) return true;ListNode p = head;while (p != null) {stk.push(p.val);p = p.next;}while (head != null){if(head.val == stk.peek()) {stk.pop();} else return false;head = head.next;}return true;}// 作者: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/}
