题目
思路
- 思路一:通过快慢指针找到中点,然后使用栈把后半部分保存。再通过出栈跟前一半进行比较,判断是否为回文链表
- 思路二:通过计算模拟hash值来判断是否回文
- 思路三:通过快慢指针找到中点,将后半部分逆转,再判断前一部分和后一部分是否一致
代码
public boolean isPalindrome(ListNode head) { if(head == null) return true; ListNode fast = head, slow = head, end = null; boolean flag = true; while(fast != null) { if(fast.next == null) { fast = fast.next; flag = false; } else { fast = fast.next.next; slow = slow.next; } } end = slow; fast = head; if(!flag) slow = slow.next; Stack<ListNode> stack = new Stack<>(); while(slow != null) { stack.push(slow); slow = slow.next; } while(!stack.isEmpty() && !fast.equals(end)) { if(fast.val == stack.pop().val) { fast = fast.next; }else return false; } if(fast.equals(end) && stack.size() == 0) return true; return false; } public boolean isPalindrome(ListNode head) { float s1 = 0,s2 = 0,t = 1; while(head != null) { s1 = s1*10 + head.val; s2 = s2 + t*head.val; t = t*10; head = head.next; } return s1 == s2; } //思路三 public boolean isPalindrome(ListNode head) { if (head == null) return true; ListNode fast = head, slow = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next == null ? fast.next : fast.next.next; } ListNode prev = null; while (slow != null) { ListNode t = slow.next; slow.next = prev; prev = slow; slow = t; } while (head != null && prev != null) { if (head.val != prev.val) return false; head = head.next; prev = prev.next; } return true; }
回文链表