题解 | 判断一个链表是否为回文结构
判断一个链表是否为回文结构
https://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
public ListNode copyList(ListNode head) {
ListNode copy = new ListNode(-1);
ListNode res = copy;
while (head != null) {
res.next = new ListNode(head.val);
res = res.next;
head = head.next;
}
return copy.next;
}
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null)return head;
ListNode pre = null, cur = head;
while (cur != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
public boolean isPail (ListNode head) {
ListNode head_ = copyList(head);
ListNode _head = reverseList(head);
while (head_ != null) {
if (head_.val != _head.val) {
return false;
}
head_ = head_.next;
_head = _head.next;
}
return true;
}
}