본문 바로가기

00/algorithm

Swap Nodes in Pairs (in Python)

반응형

Problem

Given a linked list, swap every two adjacent nodes and return its head.


Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.

Note:

Your algorithm should use only constant extra space.

You may not modify the values in the list's nodes, only nodes itself may be changed.


Solution


•current 노드를 저장해뒀다가 다음 라운드에서 next 변경해줘야함.


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
class Solution:
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
 
        if head == None :
            return head
 
        LN = None
        CN = head
        
        while CN and CN.next :
            
            NN = CN.next
 
            if LN :
                LN.next = NN
            else :
                head = NN
 
            CN.next, NN.next = NN.next, CN
            LN = CN
            CN = CN.next
        
        return head
cs




Source

https://leetcode.com/problems/swap-nodes-in-pairs/

반응형