-
linked list๊ฐ ๋ค์ด์์ ๋, ํ์๋ฒ์งธ ๋ ธ๋์ ์ง์๋ฒ์งธ ๋ ธ๋๋ฅผ ์์๋๋ก ๋ฐ๋ก ๋ชจ์ผ๊ณ , ํ์๋ฒ์งธ ๋ ธ๋ ๋ฆฌ์คํธ -> ์ง์๋ฒ์งธ ๋ ธ๋ ๋ฆฌ์คํธ๋ก ์ถ๋ ฅํ๋ผ๋ ๋ฌธ์ ๋ค.
๋จผ์ ์์ธ์ฌํญ์ ์ฒดํฌํด์ฃผ๊ณ , ๊ทธ ๋ค flag๋ฅผ ๋ฌ์ ์ง์๋ฒ์งธ์ธ์ง ํ์๋ฒ์งธ์ธ์ง ๊ตฌ๋ถํ๋ฉด์ ๊ฐ๊ฐ์ linked list์ ์ฐ๊ฒฐํด์ฃผ๊ณ , ๋ง์ง๋ง์ ํ์ ๋ฆฌ์คํธ์ next๋ฅผ ์ง์ ๋ฆฌ์คํธ์ head๋ก ์ฐ๊ฒฐํด์ฃผ์๋ค.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* oddEvenList(ListNode* head) { if (head == NULL) return NULL; else if (head->next == NULL) return head; ListNode* oddhead = head; ListNode* evenhead = head->next; ListNode* odd = oddhead; ListNode* even = evenhead; head = head->next->next; oddhead->next = NULL; evenhead->next = NULL; int flag = 1; while (head!= NULL){ if (flag == 1){ odd->next = head; odd = odd->next; head = head->next; odd->next = NULL; flag = 0; } else{ even->next = head; even = even->next; head = head->next; even->next = NULL; flag = 1; } } odd->next = evenhead; return oddhead; } };
'๐STUDY > ๐ coding test๋๋น' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode] 2. Add Two Numbers (0) 2022.01.15 [LeetCode] 59. Spiral Matrix II (0) 2022.01.15 [๋ฐฑ์ค] 1158๋ฒ ์์ธํธ์ค ๋ฌธ์ (0) 2020.02.08 ๋๊ธ