328: Are the Test Cases Correct?


  • 0
    E

    For "odd even linked list," my code gets the correct answer when I click "run code," but the further testing when I click "submit solution" insists that I'm wrong. However, the supposedly "correct" answer doesn't make sense:
    http://imgur.com/BDanTxl

    Unless I'm interpreting the question wrong, the expected answer seems weird. Here's my code:

    public class Solution {
        public ListNode oddEvenList(ListNode head) {
            int sum = 0;
            while(head != null){
                sum++;
                head = head.next;
            }
            if(sum <= 2){
                return head;
            }
            ListNode oddNode = new ListNode(1);
            ListNode oddTail = oddNode;
            ListNode evenNode = new ListNode(2);
            ListNode evenTail = evenNode;
            for(int i = 3; i <= sum; i++){
                if(i % 2 == 0){
                    evenTail.next = new ListNode(i);
                    evenTail = evenTail.next;
                }
                else{
                    oddTail.next = new ListNode(i);
                    oddTail = oddTail.next;
                }
            }
            oddTail.next = evenNode;
            return oddNode;
        }
    }
    

  • 1
    A

    [2,4,6,7,1,3,5,8] is the correct answer. Remember that we don't care about the values in the list, only their positions. So the head node is odd, the next one is even, and so on. So on input [2,1,4,3,6,5,7,8], the odd values are [2,4,6,7] and the even values are [1,3,5,8].


Log in to reply
 

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