回文链表

题目描述:请判断一个链表是否为回文链表。

示例说明请见LeetCode官网。

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

解法一:链表遍历

首先,如果head为空或者只有一个节点,直接返回true。

当head大于1个节点时,首先遍历链表,用count记录链表节点的个数为count,然后将链表的前count/2个放入一个栈中,然后将链表中的后一半节点和栈中的元素进行比较,如果有不同的,则返回false。如果都相同,最后返回true。

  1. import java.util.Stack;
  2. public class LeetCode_234 {
  3. public static boolean isPalindrome(ListNode head) {
  4. if (head == null || head.next == null) {
  5. return true;
  6. }
  7. ListNode cur = head;
  8. // 链表节点的个数
  9. int count = 0;
  10. while (cur != null) {
  11. count++;
  12. cur = cur.next;
  13. }
  14. // 将前面的一半节点放入栈中
  15. Stack<Integer> temp = new Stack<>();
  16. ListNode newCur = head;
  17. for (int i = 1; i <= count / 2; i++) {
  18. temp.push(newCur.val);
  19. newCur = newCur.next;
  20. }
  21. int start;
  22. if (count % 2 == 0) {
  23. start = count / 2 + 1;
  24. } else {
  25. start = count / 2 + 2;
  26. newCur = newCur.next;
  27. }
  28. for (int i = start; i <= count; i++) {
  29. if (temp.pop() != newCur.val) {
  30. return false;
  31. }
  32. newCur = newCur.next;
  33. }
  34. return true;
  35. }
  36. public static void main(String[] args) {
  37. ListNode head = new ListNode(1);
  38. head.next = new ListNode(0);
  39. head.next.next = new ListNode(1);
  40. System.out.println(isPalindrome(head));
  41. }
  42. }

【每日寄语】 为别人鼓掌的人也是在给自己的生命加油。