Algorithm/LEET CODE ( 파이썬 알고리즘 인터뷰)
[LEET CODE] 24. Swap Nodes in Pairs
newnu
2021. 3. 23. 00:29
반응형
# Problem
Given a linked list, swap every two adjacent nodes and return its head. ![]()
Constraints:
|
# My Answer
# 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 is None or head.next is None :
return head
# 처음 페어 바꾸기
node = head.next
node.next,node.next.next = head,head.next.next
head = node
node = node.next
while node.next and node.next.next:
temp = node.next
node.next = node.next.next
node = node.next
temp.next = node.next
node.next = temp
node = node.next
return head
# Solution 1 - 값만 교환
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
cur = head
while cur and cur.next:
# 값만 교환
cur.val, cur.next.val = cur.next.val, cur.val
cur = cur.next.next
return head
# Solution 2 - 반복 구조로 스왑
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def swapPairs(self, head: ListNode) -> 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
# Solution 3 - 재귀 구조로 스왑
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if head and head.next:
p = head.next
# 스왑된 값 리턴 받음
head.next = self.swapPairs(p.next)
p.next = head
return p
return head
반응형