Untitled
unknown
plain_text
a year ago
2.5 kB
6
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) { if(head == null){ return null; } int lenOfLL = lenLL(head); int[] oddElements = new int[lenOfLL]; int[] evenElements = new int[lenOfLL]; for(int i = 0;i < oddElements.length;i++){ oddElements[i] = Integer.MAX_VALUE; evenElements[i] = Integer.MAX_VALUE; } 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; } } ListNode head2 = null; int idx1 = 0,idx2 = 0; while (oddElements[idx1] != Integer.MAX_VALUE) { head2 = insertEnd(head2, oddElements[idx1]); if(lenOfLL >= 2){ idx1++; continue; } else{ break; } } if(lenOfLL >= 2){ while (evenElements[idx2] != Integer.MAX_VALUE) { head2 = insertEnd(head2, evenElements[idx2]); idx2++; continue; } } return head2; } }