本文共 1094 字,大约阅读时间需要 3 分钟。
对input进行修改,后半段反转。但是反转链表还是不熟啊,这怎么行!!!反转之后的尾节点的next为null。剩下看注释
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public boolean isPalindrome(ListNode head) { ListNode fast = head; ListNode slow = head; while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; } // 总结点数为奇数,为满足下方while判断,slow要后移一位 if (fast != null) { slow = slow.next; } ListNode tail = reverse(slow); // 不能是head != null,因为前半段的尾节点未置为空 while (tail != null) { if (tail.val != head.val) { return false; } tail = tail.next; head = head.next; } return true; } private ListNode reverse(ListNode head) { ListNode pre = null; while (head != null) { ListNode next = head.next; head.next = pre; pre = head; head = next; } return pre; }}
转载地址:http://tvhld.baihongyu.com/