https://leetcode.com/problems/odd-even-linked-list/description
Odd Even Linked List - LeetCode
Can you solve this real interview question? 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 od
leetcode.com
Q. input list head가 주어질때, 홀수끼리먼저 리스트를 만들고 다음에 짝수끼리 만든후에 서로 연결하라.
그리고 그 head를 반환하라.
TC O(N), SC O(1) 이 되도록 풀어라.
Solution.
단일 링크드리스트의 연결, 재조작에 대해 이해하는지 뭍는 문제.
O(N)이 되어야 하므로, 루프를 돌면서 지나간 링크에 대해 값을 바로 in place로 재 설정한다.
ListNode* oddEvenList(ListNode* head)
{
if (head == NULL || head->next == NULL)
return head;
ListNode* odd = head;
ListNode* even = head->next;
ListNode* evenHead = even;
while (even!=NULL && even->next!=NULL)
{
odd->next = even->next;
odd = even->next;
even->next = odd->next;
even = odd->next;
}
odd->next = evenHead;
return head;
}
'Leetcode > LeetCode75' 카테고리의 다른 글
[Linked List][Medium] 2130. Maximum Twin Sum of a Linked List (1) | 2023.12.19 |
---|---|
[Linked List][Easy] 206. Reverse Linked List (0) | 2023.12.18 |
[Linked List][Medium] 2095. Delete the Middle Node of a Linked List (0) | 2023.12.16 |
[Stack][Medium] 735. Asteroid Collision (0) | 2023.12.12 |
[Stack][Medium] 2390. Removing Stars From a String (0) | 2023.12.12 |