Java Solution better than 98% of solutions


  • 6
    A
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode oddEvenList(ListNode head) {
            if(head != null){
                if(head.next == null || head.next.next == null){
                    return head;
                }
                else {
                    ListNode odd = head;
                    ListNode even = head.next;
                    ListNode even1 = head.next;
                    while (even != null && even.next != null) {
                        odd.next = even.next;
                        odd = odd.next;
                        even.next = odd.next;
                        even = even.next;
                    }
                    odd.next = even1 ;
                }
            }
            return head;
        }
    }

  • 0
    W

    improved version:

    public class Solution {
        public ListNode oddEvenList(ListNode head) {
            if (head == null || head.next == null || head.next.next == null) return head;
            ListNode evenHead = head.next, evenPtr = head.next;
            ListNode oddPtr = head;
            while (evenPtr != null && evenPtr.next != null) {
                oddPtr.next = evenPtr.next;
                oddPtr = oddPtr.next;
                evenPtr.next = oddPtr.next;
                evenPtr = evenPtr.next;
            }
            oddPtr.next = evenHead;
            return head;
        }
    }

  • 0

    Could not understand very well,
    ke yi jie shi yi xia ma? T.T


Log in to reply
 

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