当前位置 博文首页 > Yawn:Leetcode——回文链表
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
解法一:
通俗解法:将值复制到数组中后用双指针法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
ListNode cur1 = head;
ListNode cur2 = head;
int len = 0;
while(cur1 != null){
cur1 = cur1.next;
len++;
}
int[] temp = new int[len];
for(int i = 0; i < len; i++){
if(cur2 != null){
temp[i] = cur2.val;
cur2 = cur2.next;
}
}
int left = 0, right = len - 1;
while(left < right){
if(temp[left] != temp[right]){
return false;
}
left++;
right--;
}
return true;
}
}
解法二:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
ListNode cur1 = head;
ListNode cur2 = head;
Stack<Integer> stack = new Stack<>();
int n = 0;
while(cur1 != null){
cur1 = cur1.next;
n++;
}
for(int i = 0; i < n; i++){
stack.push(cur2.val);
cur2 = cur2.next;
}
for(int i = 0; i < n; i++){
if(stack.pop() != head.val)
return false;
head = head.next;
}
return true;
}
}
cs