LeetCode 283. 判断一个链表是否为回文链表
请判断一个链表是否为回文链表。 示例 1: 输入: 1->2 输出: false 示例 2: 输入: 1->2->2->1 输出: true
//O(n)空间和时间复杂度 class Solution { public boolean isPalindrome(ListNode head) { // 使用栈,先让所有元素进栈,然后再出栈与链表的头部元素开始比较 LinkedList<Integer> stack = new LinkedList<>(); ListNode temp = head; while(temp!=null){ stack.push(temp.val); temp = temp.next; } ListNode temp2 = head; while(temp2!=null){ if(temp2.val != stack.pop()) return false; temp2 = temp2.next; } return true; } }
//O(n)的时间复杂度 O(1)的空间复杂度 /* 1.通过快慢指针,来遍历链表,当快指针走到末尾时,慢指针即指向链表中点 2.将后半段反转 3.将后半段与前半段进行对比,如果data相同,则继续遍历,直至到达末尾,return ture, 如果中间匹配不相同,return false */ class Solution { public boolean isPalindrome(ListNode head) { //使用快慢两个指针,快指针比慢指针多一步移动 if(head == null || head.next == null){ return true; } ListNode quick = head; ListNode slow = head; while(quick!=null && quick.next!=null){ quick = quick.next.next; slow = slow.next; } //从中间元素开始,将后面的元素翻转 ListNode pre = null; ListNode p =slow; while(p!=null){ ListNode temp = p.next; p.next = pre; pre = p; p = temp; } //将反转后的链表 与 前半段链表元素一一比较 while(pre != null){ if(pre.val == head.val){ pre = pre.next; head = head.next; } else{ return false; } } return true; } }
class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public static void main(String[] args) { //测试 ListNode head = new ListNode(1); ListNode p2 = new ListNode(2); ListNode p3 = new ListNode(2); ListNode p4 = new ListNode(1); head.next = p2; p2.next = p3; p3.next = p4; System.out.println(isPalindrome(head)); }