前言
回文链表的判断最适合用栈。
实现原理
1.找到链表中间节点。
2.反转后半段节点。
3.从头比较链表头节点的值和反转后的链表值。
具体代码实现
/**
* 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) {
boolean flag=true;
ListNode slow=head;
ListNode fast=head;
while(fast!=null&&fast.next!=null){
slow=slow.next;
fast=fast.next.next;
}
slow=reverse(slow);
while(slow!=null){
if(head.val!=slow.val){
flag=false;
}
slow=slow.next;
head=head.next;
}
return flag;
}
public ListNode reverse(ListNode head){
ListNode prev=null;
while(head!=null){
ListNode next= head.next;
head.next=prev;
prev=head;
head=next;
}
return prev;
}
}
QA:待定