본문 바로가기
알고리즘/leetcode

24. Swap Nodes in Pairs - python

by 1.5볼트 2023. 5. 19.
728x90

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

 

Swap Nodes in Pairs - LeetCode

Can you solve this real interview question? Swap Nodes in Pairs - Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be chan

leetcode.com

 

 

노드를 순회 하면서 2개씩 리스트에 넣고 2개가 채워지면 다시 리스트에 넣어 이중 리스트를 만든다 
2개씩 들어있는 리스트의 순서를 바꿔야하니까 
넣은 순서대로 꺼내준다 

 

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        p=[]
        i=0
        t=[]
        while True:
            
            if i%2==0:
                if t:
                    p.append(t)
                t=[] 
            if not head:
                break
            t.append(head.val)
            #p.append(head.val)
            head=head.next
            i+=1
        if t:
            p.append(t)
        h=None
        print(p)
        while p:
            for i in p.pop():
                if not h:
                    h=ListNode(i)
                else:
                    h=ListNode(i,h)
        return h

'알고리즘 > leetcode' 카테고리의 다른 글

2260. Minimum Consecutive Cards to Pick Up  (1) 2023.05.26
347. Top K Frequent Elements  (0) 2023.05.25
1721. Swapping Nodes in a Linked List - python  (0) 2023.05.16
59. Spiral Matrix II - python  (0) 2023.05.10
54. Spiral Matrix - python  (0) 2023.05.09

댓글