DESC:
编写一个函数,检查输入的链表是否是回文的。
示例 1:
输入: 1->2
输出: false示例 2:
输入: 1->2->2->1
输出: true进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-linked-list-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
CODE1:
JAVA:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public boolean isPalindrome(ListNode head) { if (head == null || head.next==null) { return true; } List<Integer> list = new ArrayList<>(); ListNode temp = head; while (temp!=null) { list.add(temp.val); temp = temp.next; } boolean res = true; for (int i=0,j=list.size()-1; i<j; i++,j--) { if (!list.get(i).equals(list.get(j))) { res = false; break; } } return res; } }
Python:
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def isPalindrome(self, head: Optional[ListNode]) -> bool: if not head: return False arr = [] while head: arr.append(head.val) head = head.next left=0 right=len(arr)-1 while left<=right: if arr[left] != arr[right]: return False left += 1 right -= 1 return True
NOTES1:
- 集合+双指针
- 遍历链表拿到所有值,再用双指针进行判断回文
- 时间空间复杂度都是O(n)
CODE2:
JAVA:
class Solution { public boolean isPalindrome(ListNode head) { if (head == null) { return true; } // 找到前半部分链表的尾节点并反转后半部分链表 ListNode firstHalfEnd = endOfFirstHalf(head); ListNode secondHalfStart = reverseList(firstHalfEnd.next); // 判断是否回文 ListNode p1 = head; ListNode p2 = secondHalfStart; boolean result = true; while (result && p2 != null) { if (p1.val != p2.val) { result = false; } p1 = p1.next; p2 = p2.next; } // 还原链表并返回结果 firstHalfEnd.next = reverseList(secondHalfStart); return result; } private ListNode reverseList(ListNode head) { ListNode prev = null; ListNode curr = head; while (curr != null) { ListNode nextTemp = curr.next; curr.next = prev; prev = curr; curr = nextTemp; } return prev; } private ListNode endOfFirstHalf(ListNode head) { ListNode fast = head; ListNode slow = head; while (fast.next != null && fast.next.next != null) { fast = fast.next.next; slow = slow.next; } return slow; } }
NOTES2:
- 使用快慢指针找到链表中间节点,将后半部分链表反转,与前半部分递归进行回文判断
- 修改了原链表结构