Modified Odd Even Linked List

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.6 kB
2
Indexable
Never
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public static ListNode insertEnd(ListNode head, int x) {
        ListNode temp = new ListNode(x);
        if (head == null) {
            return temp;
        }
        ListNode curr = head;
        while (curr.next != null) {
            curr = curr.next;
        }
        curr.next = temp;
        return head;

    }

    public static int lenLL(ListNode head) {
        ListNode curr = head;
        int length = 0;
        while (curr != null) {
            length++;
            curr = curr.next;
        }
        return length;
    }

    public static ListNode oddEvenList(ListNode head) {
        int lenOfLL = lenLL(head);
        int[] oddElements = new int[lenOfLL];
        int[] evenElements = new int[lenOfLL];
        ListNode curr = head;
        int pos = 1;
        int oddIdx = 0, evenIdx = 0;
        while (curr != null) {
            if ((pos % 2) != 0) {
                oddElements[oddIdx] = curr.val;
                oddIdx++;
                pos++;
                curr = curr.next;
                continue;
            } else if ((pos % 2) == 0) {
                evenElements[evenIdx] = curr.val;
                evenIdx++;
                curr = curr.next;
                pos++;
                continue;
            }
        }
        for (int i = 0; i < evenElements.length; i++) {
            System.out.print(evenElements[i] + " ");
        }
        System.out.println();
        for (int i = 0; i < oddElements.length; i++) {
            System.out.print(oddElements[i] + " ");
        }
        ListNode curr2 = head;
        int firstVal = curr2.val;
        ListNode head2 = null;
        ListNode finalHead = null;
        int idx1 = 0, idx2 = 0;
           
            head2 = null;
            idx1 = 0;
            while (oddElements[idx1] > 0) {
                head2 = insertEnd(head2, oddElements[idx1]);
                idx1++;
                continue;
            }
           
            idx2 = 0;
            while (evenElements[idx2] > 0) {
                head2 = insertEnd(head2, evenElements[idx2]);
                idx2++;
                continue;
            }
            
            finalHead = head2;
      
        return finalHead;
    }
}