18. 홀짝 연결리스트
https://leetcode.com/problems/odd-even-linked-list/
Odd Even Linked List - LeetCode
Odd Even Linked List - 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. N
leetcode.com
📌문제
연결 리스트를 홀수 노드 다음에 짝수 노드가 오도록 재구성하라. 공간 복잡도 O(1), 시간 복잡도O(n)에 풀이하라
- 예제1
📝입력
head = [1,2,3,4,5]
💻출력
[1,3,5,2,4]
- 예제2
📝입력
head = [2,1,3,5,6,4,7]
💻출력
[2,3,6,7,1,5,4]
📌풀이
0ms, 41.6mb
/**
* 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 || head.next == null) {
return head;
}
ListNode odd = head, even = head.next, evenHead = head.next;
while (even != null && even.next != null) {
odd.next = odd.next.next;
even.next = even.next.next;
odd = odd.next;
even = even.next;
}
odd.next = evenHead;
return head;
}
}
- odd: 홀수 even 짝수
- 페어의 노드스왑으로 큰 깨달음을 얻으니까 이 풀이도 쉬워보이더라..
- 소스 그대로 2칸씩 next를 이어가는 방법
'Algorithm > PTUStudy' 카테고리의 다른 글
8주차. 스택,큐 (중복 문자 제거) (0) | 2023.03.30 |
---|---|
8주차. 스택, 큐(유효한 괄호) (0) | 2023.03.30 |
6-7주차 연결 리스트(페어의 노드 스왑) (0) | 2023.02.16 |
7주차. 연결리스트 복습(두 정렬 리스트의 병합) (0) | 2023.02.16 |
6주차. 연결리스트(두 수의 덧셈) (0) | 2023.02.16 |