判断一个链表是否是回文结构
判断一个链表是否为回文结构
https://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f?tpId=117&tags=&title=&diffculty=0&judgeStatus=0&rp=1&tab=answerKey
private ListNode sList(ListNode slow){
ListNode pre = new ListNode(1);
pre.next = null;
while(slow!=null){
ListNode temp = slow.next;
slow.next = pre.next;
pre.next = slow;
slow = temp;
}
return pre.next;
}
//将链表的后半部分进行反转
public boolean isPail (ListNode head) {
// write code here
ListNode slow = head;
ListNode fast = head;
ListNode pre =new ListNode(0);
pre.next = head;
while(fast!=null && fast.next!=null){
fast = fast.next.next;
slow = slow.next;
pre = pre.next;
}
if(fast!=null){
pre = pre.next;
slow = slow.next;
}
slow = sList(slow);
while(slow!=null){
if(head.val!=slow.val) return false;
head = head.next;
slow = slow.next;
}
slow = sList(slow);//将反转的链表还原
pre.next = slow;
return true;
}
查看17道真题和解析

