逆序打印链表
var reverse = function(head){
if(head==null) return;
reverse(head.next);
console.log(head.val);
}
判断回文链表
思路
快慢指针反转中点之后的链表,然后双指针从两端往中间逼近。
代码
var isPalindrome = function(head) {
let slow = head;
let fast = head;
while(fast!=null && fast.next!=null){
slow = slow.next;
fast = fast.next.next;
}
if(fast!=null){
slow = slow.next;
}
let left = head;
let right = reverse(slow);
while(left!=null && right!=null){
if(left.val!=right.val){
return false;
}
left = left.next;
right = right.next;
}
return true;
};
var reverse = function(head){
if(head==null) return head;
let pre = null;
let curr = head;
let nxt = curr.next;
while(curr!=null){
nxt = curr.next;
curr.next = pre;
pre = curr;
curr = nxt;
}
return pre;
}