回文链表
编写一个函数,检查输入的链表是否是回文的。
第一种解法:利用栈来进行存储节点值,因为栈的先进后出特性。
public boolean isPalindrome(ListNode head) {
Stack<Integer> s=new Stack();
ListNode node=head;
while(node!=null){
s.push(node.val);
node=node.next;
}
ListNode temp=head;
while(temp!=null){
if(temp.val!=s.peek()){
return false;
}
s.pop();
temp=temp.next;
}
return true;
}
时间复杂度为o(n),空间复杂度为o(n).
第二种解法:先找到链表的中点,利用快慢指针来找中点,然后将中点以后的数据反转,最后前后进行遍历比较,多余话不说来看代码。
public boolean isPalindrome(ListNode head) {
ListNode left=head;
ListNode rigth=head;
while(rigth!=null&&rigth.next!=null){
left=left.next;
rigth=rigth.next.next;
}
ListNode temp,root=null;
while(left!=null){
temp=left.next;
left.next=root;
root=left;
left=temp;
}
ListNode node=head;
while(root!=null){
if(root.val!=node.val){
return false;
}
root=root.next;
node=node.next;
}
return true;
}
时间复杂度为o(n),空间复杂度为o(1).