https://leetcode.com/problems/odd-even-linked-list
LinkedList 있으면 짝수 idx의 원소들 쌓고 이어서 홀수idx의 원소들 쌓기
public ListNode oddEvenList(ListNode head) {
if (head == null) {
return null;
}
List<ListNode> inList = new ArrayList<>();
int idx = 1;
ListNode tmp = head;
while (tmp != null) {
if (idx % 2 == 1) {
inList.add(tmp);
}
tmp = tmp.next;
idx++;
}
idx = 1;
tmp = head;
while (tmp != null) {
if (idx % 2 == 0) {
inList.add(tmp);
}
tmp = tmp.next;
idx++;
}
for (int i = 0; i < inList.size() - 1; i++) {
inList.get(i).next = inList.get(i + 1);
}
inList.get(inList.size() - 1).next = null;
return head;
}
public ListNode oddEvenList(ListNode head) {
if (head == null) {
return null;
}
ListNode odd = head;
ListNode even = head.next;
ListNode evenHead = even;
while (even != null && even.next != null) {
odd.next = even.next;
odd = odd.next;
even.next = odd.next;
even = even.next;
}
// 홀수 끝나고 짝수랑 이어주는 부분
odd.next = evenHead;
return head;
}
이런 멋진 방법이..