2021년/알고리즘

[파이썬 알고리즘 인터뷰] 역순 연결리스트

위지원 2021. 3. 31. 11:33

(19) 역순 연결리스트 

github.com/onlybooks/algorithm-interview

★Normal

 

[LeetCode]

 

 

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

 


풀이법

짝/홀이 정해진 규칙대로 나오기 때문에 시작점만 다르게 잡아주고 이동시켜주면서 붙여주면된다.

 

 python

class Solution:
    def oddEvenList(self, head: ListNode) -> ListNode:
        if head is None:
            return None
        
        odd = head
        
        even = head.next
        even_head = head.next
        
        while even and even.next:
            odd.next = odd.next.next
            even.next = even.next.next
            
            odd = odd.next 
            even = even.next
            
        odd.next = even_head
        
        return head

 

java

class Solution {
    public ListNode oddEvenList(ListNode head) {
        if(head == null)
            return null;
        
        ListNode odd = head;
        ListNode even = head.next;
        ListNode evneHead = head.next;
        
        while(even != null && even.next != null){
            odd.next = odd.next.next;
            even.next = even.next.next;
            odd = odd.next;
            even = even.next;
        }
        
        odd.next = evneHead;
        return head;
        
    }
}