判断一个链表是否为回文结构
作者:互联网
请判断一个链表是否为回文链表
思路:栈,需要想一下链表的结点个数的奇偶性:快慢指针找到链表的后半段,并存入栈中(链表长度为奇数的话就是中间结点的下一个),然后比较栈中元素和前半段元素
class Solution {
public boolean isPalindrome(ListNode head) {
if (head==null || head.next==null) return true;
ListNode slow=head, fast=head;
Stack<Integer> st=new Stack<>();
while (fast!=null && fast.next!=null) {
slow=slow.next;
fast=fast.next.next;
}
while (slow!=null) {
st.push(slow.val);
slow=slow.next;
}
while (!st.isEmpty()) {
if (st.pop()!=head.val) return false;
head=head.next;
}
return true;
}
}
O(1)空间解法:将链表的后半段翻转然后和前半段比较
class Solution {
ListNode reverse(ListNode head) {
if (head==null || head.next==null) return head;
ListNode pre=null, post=head;
while (head!=null) {
post=head.next;
head.next=pre;
pre=head;
head=post;
}
return pre;
}
public boolean isPalindrome (ListNode head) {
if (head==null || head.next==null) return true;
ListNode slow=head, fast=head;
while (fast!=null && fast.next!=null) {
slow=slow.next;
fast=fast.next.next;
}
slow=reverse(slow);
while (slow!=null) {
if (slow.val!=head.val) return false;
slow=slow.next;
head=head.next;
}
return true;
}
}
标签:head,slow,return,回文结构,fast,next,链表,判断,null 来源: https://www.cnblogs.com/wdt1/p/13946225.html