【LeetCode】234. Palindrome Linked List
Difficulty:easy
More:【目录】LeetCode Java实现
Description
https://leetcode.com/problems/palindrome-linked-list/
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2 Output: false
Example 2:
Input: 1->2->2->1 Output: true
Follow up:
Could you do it in O(n) time and O(1) space?
Intuition
Mehtod 1. reverse the right half of the list
Method 2. use a stack to store
Solution
//Method 1: reverse half of the list
public boolean isPalindrome(ListNode head) {
if(head==null)
return true;
ListNode slow = head, fast = head;
while(fast!=null && fast.next!=null){
slow = slow.next;
fast = fast.next.next;
}
if(fast!=null) // odd nodes: let right half smaller
slow = slow.next;
slow = reverse(slow);
while(slow!=null){
if(head.val != slow.val)
return false;
head=head.next;
slow=slow.next;
}
return true;
}
public ListNode reverse(ListNode node){
ListNode pre = null;
ListNode cur = node;
while(cur!=null){
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
//Method 2: use a stack to store
public boolean isPalindrome1(ListNode head) {
Stack<ListNode> stack = new Stack<>();
ListNode node = head;
while(node!=null){
stack.push(node);
node=node.next;
}
while(!stack.isEmpty()){
if(head.val != stack.pop().val)
return false;
head=head.next;
}
return true;
}
Complexity
Method 1: (it will modify the original list)
Time complexity : O(n)
Space complexity : O(1)
Method 2:
Time complexity : O(n)
Space complexity : O(n)
More:【目录】LeetCode Java实现

浙公网安备 33010602011771号