Odd Even Linked List

2021. 7. 7. 16:29· 자료구조 알고리즘/코딩테스트

328. Odd Even Linked List

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

 

Odd Even Linked List - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 Language: C++

time: O(n), space: O(1)

/**
 * 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) {
            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;
    }
};

이게 더 이해하기 쉽기도 하고 런타임은 빠르다

class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        if(!head) return NULL;
        ListNode* odd = head;
        ListNode* evenHead = head->next;
        ListNode* even = evenHead;
        
        while(odd->next && even->next) {
            odd->next = odd->next->next;
            odd = odd->next;
            even->next = even->next->next;
            even = even->next;
        }
        
        odd->next = evenHead;
        return 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 && head->next && head->next->next) {
            ListNode* cur = head;
            ListNode* node = cur->next;
            int lastVal = head->next->val;
            do {
                node = cur->next;
                cur->next = node->next;
                ListNode* temp = cur->next;
                node->next = NULL;
                while(temp->next != NULL) {
                    temp = temp->next;
                }
                temp->next = node;
                cur = cur->next;
            } while (cur->val != lastVal && cur->next->val != lastVal);
            
        }
        return head;
    }
};

문제점

접근 방식이 나는 그냥 원래 리스트에서 노드의 값이 다 다르다는 전제 하에 두번째 노드를 다시 만났을 때 멈추기로 했었는데

솔루션은 Odd Linked List, Even Linked List 이렇게 두 개를 만들어 놓고 진행했다.

Odd Linked List 에서 짝수 번째에 있는 것을 Even Linked List 로 이동시킨 후 null을 만났을 때 합체시켜주는 방식이었다.

 

728x90
반응형

'자료구조 알고리즘 > 코딩테스트' 카테고리의 다른 글

Add Two Numbers  (0) 2022.01.28
Merge Two Sorted Lists  (0) 2022.01.28
Remove Linked List Elements  (0) 2021.07.06
Reverse Linked List  (0) 2021.07.04
Remove Nth Node From End of List  (0) 2021.07.03
'자료구조 알고리즘/코딩테스트' 카테고리의 다른 글
  • Add Two Numbers
  • Merge Two Sorted Lists
  • Remove Linked List Elements
  • Reverse Linked List
내공얌냠
내공얌냠
내공냠냠
내공얌냠
내공냠냠
내공얌냠
전체
오늘
어제
  • 분류 전체보기 (254)
    • 개발 (113)
      • mediapipe (16)
      • insightface (5)
      • JongjuAR (3)
    • 자료구조 알고리즘 (79)
      • 코딩테스트 (64)
      • 이론 (15)
    • 공부 (7)
      • 단행본 (7)
      • 튜토리얼 (19)
      • 논문 (15)
      • 복기 (5)
    • 참여 (5)

블로그 메뉴

  • 홈
  • 태그
  • 미디어로그
  • 위치로그
  • 방명록

공지사항

인기 글

태그

  • mediapipe translate
  • 딥러닝 기반 음성인식 기초
  • 음성인식 기초
  • 플러터 튜토리얼
  • mediapipe
  • python telegrambot
  • vscode 스프링 설치
  • kubeflow설치가이드
  • flutter 행사 후기
  • flutter
  • 구글 미디어파이프
  • flutter 행사
  • ios google places api
  • kubeflow설치안됨
  • speaker adaptation tts
  • 미디어파이프
  • google mediapipe
  • git tutorial
  • torchscript vs onnx vs tensorrt
  • 머신러닝이란
  • 컴퓨터 비전 책 추천
  • 깃 튜토리얼
  • 플러터
  • flutter conference
  • flutter tutorial
  • 컴퓨터 비전 기초
  • 컴퓨터 비전
  • postgresql 재설치
  • 음성인식 튜토리얼
  • postgresql install in mac

최근 댓글

최근 글

hELLO · Designed By 정상우.v4.2.2
내공얌냠
Odd Even Linked List
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.