题解 | #判断一个链表是否为回文结构#
判断一个链表是否为回文结构
https://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f
判断一个链表是否为回文结构
一开始我的思路是,将整个链表反转,但修改了半天代码依然出现报错问题,没有办法只能看了看大佬的解题思路,利用了快慢指针找到中间节点,再反转中间节点后面的链表,在跟原链表进行比较,如果值都相等,则为回文结构,代码如下:
public boolean isPail (ListNode head) {
// write code here
ListNode fast = head;//快指针
ListNode slow = head;//慢指针
while (fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
}
//这里fast为空则说明链表长度为单数,需要将slow。next定为反转节点
if (fast!=null){
slow=slow.next;
}
//反转链表
slow=ReverseList(slow);
fast=head;
while (slow!=null){
if (fast.val!=slow.val){//比较反转后两链表的值
return false;
}else {
fast=fast.next;
slow=slow.next;
}
}
return true;
}
这里是反转链表的代码
public ListNode ReverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while (cur != null) {
ListNode CurNext = cur.next;
cur.next = pre;
pre = cur;
cur = CurNext;
}
return pre;
}
以上
public ListNode ReverseList(ListNode head) { ListNode pre = null; ListNode cur = head; while (cur != null) { ListNode CurNext = cur.next; cur.next = pre; pre = cur; cur = CurNext; } return pre; }以上