categories: [Blog,Algorithm]


234. 回文链表

难度简单872
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true

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

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode() {}
  7. * ListNode(int val) { this.val = val; }
  8. * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  9. * }
  10. */
  11. class Solution {
  12. public boolean isPalindrome(ListNode head) {
  13. List<Integer> vals = new ArrayList<Integer>();
  14. // 将链表的值复制到数组中
  15. ListNode currentNode = head;
  16. while (currentNode != null) {
  17. vals.add(currentNode.val);
  18. currentNode = currentNode.next;
  19. }
  20. // 使用双指针判断是否回文
  21. int front = 0;
  22. int back = vals.size() - 1;
  23. while (front < back) {
  24. if (!vals.get(front).equals(vals.get(back))) {
  25. return false;
  26. }
  27. front++;
  28. back--;
  29. }
  30. return true;
  31. }
  32. // 作者:LeetCode-Solution
  33. // 链接:https://leetcode-cn.com/problems/palindrome-linked-list/solution/hui-wen-lian-biao-by-leetcode-solution/
  34. }

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode() {}
  7. * ListNode(int val) { this.val = val; }
  8. * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  9. * }
  10. */
  11. class Solution {
  12. public boolean isPalindrome(ListNode head) {
  13. Stack<Integer> stk =new Stack();
  14. if (null==head || null==head.next) return true;
  15. ListNode p = head;
  16. while (p != null) {
  17. stk.push(p.val);
  18. p = p.next;
  19. }
  20. while (head != null){
  21. if(head.val == stk.peek()) {
  22. stk.pop();
  23. } else return false;
  24. head = head.next;
  25. }
  26. return true;
  27. }
  28. // 作者:wo-yao-chu-qu-luan-shuo
  29. // 链接:https://leetcode-cn.com/problems/palindrome-linked-list/solution/hui-wen-lian-biao-fu-zhu-zhan-by-wo-yao-ab2uc/
  30. }