반응형
# 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
반응형
'Algorithm > LEET CODE ( 파이썬 알고리즘 인터뷰)' 카테고리의 다른 글
[LEET CODE] 92. Reverse Linked List II (0) | 2021.03.23 |
---|---|
[LEET CODE] 328. Odd Even Linked List (0) | 2021.03.23 |
[LEET CODE] 2. Add Two Numbers ( 숫자형 리스트 병합하기) (0) | 2021.03.22 |
[LEET CODE] 206. Reverse Linked List (0) | 2021.03.22 |
[LEET CODE] 21. Merge Two Sorted Lists ( 연산자 우선순위, 변수 스왑) (0) | 2021.03.22 |