[leetcode #328] Odd Even Linked List

Seongyeol Shin·2021년 12월 2일
0

leetcode

목록 보기
94/196
post-thumbnail

Problem

Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.

The first node is considered odd, and the second node is even, and so on.

Note that the relative order inside both the even and odd groups should remain as it was in the input.

You must solve the problem in O(1) extra space complexity and O(n) time complexity.

Example 1:

Input: head = [1,2,3,4,5]
Output: [1,3,5,2,4]

Example 2:

Input: head = [2,1,3,5,6,4,7]
Output: [2,3,6,7,1,5,4]

Constraints:

・ n == number of nodes in the linked list
・ 0 <= n <= 10⁴
・ -10⁶ <= Node.val <= 10⁶

Idea

리스트의 포인터만 잘 옮기면 쉽게 풀 수 있는 문제다.

우선 홀수 노드의 head의 포인터와 짝수 노드의 head 포인터를 각각 저장한다. 그리고 현재 노드와 다음 노드에 대한 포인터도 각각 저장한다. 포인터를 전부 옮기고 난 뒤, 홀수 노드의 끝 부분의 next 포인터가 짝수 노드의 head를 가리키도록 해야 하므로 홀수 노드의 tail에 대한 포인터도 저장한다.

리스트를 탐색할 때 nextNode가 null이 아닐 때까지 탐색하면 된다. 홀수 노드와 짝수 노드를 grouping할 때 nextNode가 null이면 현재 노드의 next 포인터를 nextNode의 next 포인터로 바꿔줘야 하는데, nextNode가 null이면 바꿔줄 포인터가 없기 때문이다. currentNode의 next 포인터를 nextNode의 next 포인터로 바꿔준 뒤, currentNode를 nextNode로, nextNode를 currentNode의 next로 바꿔주면 grouping이 자연스럽게 된다.

그리고 cnt를 세면서 currentNode가 홀수 노드일 때 홀수 노드의 tail을 currentNode로 설정해준다.

탐색이 끝난 뒤 홀수 노드 tail의 next 포인터를 짝수 노드의 head로 바꿔주면 된다.

Solution

/**
 * 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 ListNode oddEvenList(ListNode head) {
        if (head == null) {
            return head;
        }

        int cnt = 1;

        ListNode oddHead = head;
        ListNode evenHead = head.next;
        ListNode currentNode = head;
        ListNode nextNode = head.next;
        ListNode oddTail = head;

        while (nextNode != null) {
            currentNode.next = nextNode.next;
            currentNode = nextNode;
            nextNode = currentNode.next;
            cnt++;
            if (cnt % 2 == 1) {
                oddTail = currentNode;
            }
        }

        oddTail.next = evenHead;

        return oddHead;
    }
}

Reference

https://leetcode.com/problems/odd-even-linked-list/

profile
서버개발자 토모입니다

0개의 댓글