Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 1주일회고
- 99클럽
- TiL
- 디자인 패턴
- Spring multimodule
- 취업리부트코스
- KPT회고
- jwt
- @FeignClient
- 인프콘 2024
- 파이썬
- infcon 2024
- 커스텀 헤더
- 코딩테스트 준비
- 프로그래머스 이중우선순위큐
- jwttoken
- 프로그래머스
- 빈 충돌
- spring batch 5.0
- 디자인패턴
- 개발자부트캠프추천
- 단기개발자코스
- DesignPattern
- JavaScript
- 개발자 취업
- 전략패턴 #StrategyPattern #디자인패턴
- Python
- 빈 조회 2개 이상
- 항해99
- 구글 OAuth login
Archives
- Today
- Total
m1ndy5's coding blog
LeetCode 328. Odd Even Linked List with Python 본문
https://leetcode.com/problems/odd-even-linked-list/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
# 아무것도 들어오지 않았을 때
if head is None:
return None
odd = head
even = head.next
even_head = head.next
# 짝수번째도 있고 그 다음 홀수번째도 있을 때
while even and even.next:
# 2개씩 건너서 연결
odd.next, even.next = odd.next.next, even.next.next
odd, even = odd.next, even.next
# 홀수 리스트 뒤에 짝수 리스트 붙임
odd.next = even_head
return head
2개씩 건나서 연결했기 1번 다음에 3번노드, 3번노드로 이동해서 5번노드랑 연결 ... 2번-4번, 4번으로 이동해서 4-6이런식으로 연결했다.
이 때 홀짝홀짝 -> 이처럼 뒤에 홀이 없으면 even.next(None)의 next를 찾게 되서 오류가 나기 때문에
while 조건문을 홀짝홀짝홀까지로 조건을 주어야한다.
'알고리즘 with python > 알고리즘 스터디' 카테고리의 다른 글
LeetCode 46.Permutations(순열) with Python (0) | 2024.01.10 |
---|---|
LeetCode 17. Letter Combinations of a Phone Number with Python (1) | 2024.01.10 |
LeetCode 21. Merge Two Sorted Lists with Python (0) | 2024.01.06 |
LeetCode 206.Reverse Linked List with Python (0) | 2024.01.06 |
LeetCode 215. Kth Largest Element in an Array with Python (0) | 2024.01.05 |