홀짝 연결리스트
5093 단어 파이썬알고리즘인터뷰연결리스트리트코드리트코드
문제
링크 https://leetcode.com/problems/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 odd, and the second node is even, and so on.
Note that the relative order inside both the even and odd groups should remain as it was in the input.
You must solve the problem in O(1) extra space complexity and O(n) time complexity.
*Example 1:
Input: head = [1,2,3,4,5]
Output: [1,3,5,2,4]
*Example 2:
Input: head = [2,1,3,5,6,4,7]
Output: [2,3,6,7,1,5,4]
코드
class Solution:
def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
oddhead = odd = ListNode()
evenhead = even = ListNode()
cnt=1
if not head or not head.next : return head
while head:
if cnt%2==1:
odd.val=head.val
odd.next=ListNode()
odd,head=odd.next,head.next
else:
even.val=head.val
head=head.next
if head and head.next :
even.next=ListNode()
even=even.next
cnt+=1
odd.val=evenhead.val
odd.next=evenhead.next
return oddhead
로직
- Odd, Even 연결리스트 생성.
- head를 탐색하며 홀수 노드와 짝수 노드에 대해 탐색 후 추가
Author And Source
이 문제에 관하여(홀짝 연결리스트), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@swany0509/홀짝-연결리스트저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)