반응형
leetcode.com/problems/swap-nodes-in-pairs/
# 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: ListNode) -> ListNode:
if head and head.next :
next = ListNode(head.val, head.next.next)
node = ListNode(head.next.val,next)
node.next.next = self.swapPairs(head.next.next)
return node
return head
# 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: ListNode) -> ListNode:
if not head or not head.next:
return head
if head and head.next.next:
head.next.next = self.swapPairs(head.next.next)
prev = head.next
head.next = head.next.next
prev.next = head
return prev
댓글