Notice
Recent Posts
Recent Comments
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
29 | 30 | 31 |
Tags
- leetcode
- Kaggle
- Baekjoon
- 더현대서울 맛집
- programmers
- 맥북
- 프로그래머스 파이썬
- ChatGPT
- 캐치카페
- Real or Not? NLP with Disaster Tweets
- 우분투
- ubuntu
- 코로나19
- 데이콘
- AI 경진대회
- 금융문자분석경진대회
- Docker
- 백준
- github
- dacon
- PYTHON
- gs25
- Git
- 자연어처리
- hackerrank
- 프로그래머스
- 편스토랑 우승상품
- SW Expert Academy
- 파이썬
- 편스토랑
Archives
- Today
- Total
솜씨좋은장씨
[leetCode] 328. Odd Even Linked List (Python) 본문
728x90
반응형
Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
Example 1:
Input: 1->2->3->4->5->NULL
Output: 1->3->5->2->4->NULL
Example 2:
Input: 2->1->3->5->6->4->7->NULL
Output: 2->3->6->7->1->5->4->NULL
Constraints:
- The relative order inside both the even and odd groups should remain as it was in the input.
- The first node is considered odd, the second node even and so on ...
- The length of the linked list is between [0, 10^4].
Solution
# 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: ListNode) -> ListNode:
odd_nums = []
even_nums = []
cnt = 0
while True:
if head == None:
break
val = head.val
if cnt % 2 == 0:
even_nums.append(val)
else:
odd_nums.append(val)
head = head.next
cnt = cnt + 1
answerList = ListNode(0)
result = answerList
for i in range(len(even_nums)):
answerList.next = ListNode(even_nums[i])
answerList = answerList.next
for i in range(len(odd_nums)):
answerList.next = ListNode(odd_nums[i])
answerList = answerList.next
return result.next
'Programming > 코딩 1일 1문제' 카테고리의 다른 글
[leetCode] 1232. Check If It Is a Straight Line (Python) (2) | 2021.02.01 |
---|---|
[leetCode] 1009. Complement of Base 10 Integer (Python) (0) | 2021.01.31 |
[leetCode] 941. Valid Mountain Array (Python) (0) | 2021.01.29 |
[leetCode] 1486. XOR Operation in an Array (Python) (0) | 2021.01.28 |
[leetCode] 476. Number Complement (Python) (0) | 2021.01.27 |
Comments