[LeetCode]234. Palindrome Linked List

来源:互联网 发布:电视怎么弄成网络电视 编辑:程序博客网 时间:2024/06/06 05:46

https://leetcode.com/problems/palindrome-linked-list/

对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;    }}


0 0
原创粉丝点击