What if we are talking about the node val instead of node number?


  • 0
    S

    I find it is interesting to group the odd and even by node number, and I am wondering what if we group the odd/even number by value ? Ex: 1246857 -> 1572468

    I tried to solve this problem, but found one problem: I have to know the first odd number and first even number. Here I assume the head.val is odd, the head.next.val is even. Below is my easy solution:

        //group by value instead of by node number
    	public ListNode oddEven(ListNode head) {
    		if(head != null) {
    			//assume the head.val is odd, head.next.val is even
    			ListNode even = head.next, odd = head, evenHead = even, cur = even.next;
    			
    			while(cur != null ) {
    				if(cur.val % 2 == 0) {
    					even.next = cur;
    					even = even.next;
    				} else {
    					odd.next = cur;
    					odd = odd.next;
    				}
    				cur = cur.next;
    			}
    			odd.next = evenHead;
    			
    		}
    		return head;
    	}  
    

    But is there anybody that could come up with a general solution so that we don't need to know the position of first odd/even number in advance ? I mean can anyone come up with a general solution that can pass all the following test case?

    2->1->3->5->6->8->7

    2->4->6->8->1


Log in to reply
 

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