[leetcode] 24. Swap Nodes in Pairs

2022. 11. 18. 10:06노트/Algorithm : 알고리즘

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 changed.)

 

Example 1:

Input: head = [1,2,3,4]
Output: [2,1,4,3]

Example 2:

Input: head = []
Output: []

Example 3:

Input: head = [1]
Output: [1]

 

Constraints:

  • The number of nodes in the list is in the range [0, 100].
  • 0 <= Node.val <= 100

 

# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        node = head 
        while node and node.next:
            node.val, node.next.val= node.next.val, node.val
            node = node.next.next
        
        return head
class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        root = prev = ListNode(None)
        prev.next = head 
        while head and head.next:
            
            # b가 a(head)를 가리키도록 할당
            b = head.next 
            head.next = b.next 
            b.next = head 
            
            # prev가 b를 가리키도록 할당 
            prev.next = b 
            
            # 다음번 비교를 위해 이동
            head = head.next
            prev = prev.next.next 
            
        return root.next