2ms java clean code with note


  • 0
    P
    /**
     * 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) {
            //判断特殊情况,head空链表活着只有一个值即为回文链表
            if(head==null || head.next==null) return true;
            //只有两个值的链表下面的判断错误,需要单独判断
            if(head.next.next==null) return head.val==head.next.val;
            //利用快慢指针确定链表中心
            ListNode slow = head;
            ListNode fast = head;
            while(fast.next!=null && fast.next.next!=null){
                fast = fast.next.next;
                slow = slow.next;
            }
            //将后半段倒置后头节点赋值给闲置的slow
            slow=reverselist(slow.next);
            // 虽然比较的是head(整段)和slow,但是比较函数按照最短处理了
            return isSame(head,slow);
        }
        //将后半段链表原地倒置
        public ListNode reverselist(ListNode node){
            ListNode temp;
            ListNode pre=null;
            ListNode cur=node;
            while(cur!=null){
                temp = cur.next;
                cur.next = pre;
                pre = cur;
                cur = temp;
            }
            return pre;
        }
        //比较链表前半段和后半段是否相同
        public boolean isSame(ListNode fa,ListNode sl){
            while(sl!=null){
                if(fa.val==sl.val){
                    fa = fa.next;
                    sl = sl.next;
                }
                else return false;
                
            }
            return true;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.