[M] 328. Odd Even Linked List

YJ·2025년 4월 27일

leetcode

목록 보기
38/100

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;
}

이런 멋진 방법이..

profile
Hello

0개의 댓글