Leetcode 234、回文链表
方法一、使用数组存储链表中的节点
思路:遍历链表,把链表中的值添加到list数组里面,然后使用双指针判断list数组是否是回文。
时间复杂度:O(N)
空间复杂度:O(N) 使用数组存储链表中的值
class Solution {
/**
快慢指针
*/
public boolean isPalindrome(ListNode head) {
if(head == null) return true;
List<Integer> list = new ArrayList<>();
while(head != null) {
list.add(head.val);
head = head.next;
}
int left = 0, right = list.size() - 1;
while(left <= right) {
if(list.get(left) != list.get(right)) {
return false;
}
left++;
right--;
}
return true;
}
}
方法二、快慢指针+栈
快慢指针,first指针移动一个位置,second移动两个位置;链表节点个数可能是奇数也可能是偶数;
-
如果节点个数是奇数,跳出第一个循环,second.next为空,弹出栈顶元素,也就是链表中间的节点值;然后first继续向下遍历和statck中的元素进行比较;
-
因为在遍历的时候,每次都把first指向的节点值入栈,所以跳出循环以后,要弹出栈顶元素;first继续向下遍历与stack栈顶元素进行比较。
-
如果节点个数是偶数,跳出循环以后second.next !=null,不需要弹出栈顶元素,直接进入第二个while循环进行判断
时间复杂度:O(N)
空间复杂度:O(1)
class Solution {
/**
快慢指针
*/
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null) return true;
Deque<Integer> stack = new LinkedList<>();
ListNode first = head;
ListNode second = head;
stack.push(first.val);
while(second.next != null) {
if(second.next.next != null) {
first = first.next;
stack.push(first.val);
second = second.next.next;
}else {
break;
}
}
if(second.next == null) {
stack.pop();
}
while(first.next != null) {
first = first.next;
int curr = stack.pop();
if(curr != first.val) {
return false;
}
}
return true;
}
}