<LeetCode 문제>
https://leetcode.com/problems/swap-nodes-in-pairs/
Swap Nodes in Pairs - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
<풀이>
연결리스트를 2칸씩이동하며 값을 swap해주면 됩니다.
# 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]:
cur=head
while cur and cur.next: #next가 존재할때
cur.val,cur.next.val = cur.next.val,cur.val #swap
cur = cur.next.next #2칸 이동
return head
<학습내용>
1.
<학습이 필요한 내용>
'Algorithm > 파이썬 알고리즘 인터뷰 스터디' 카테고리의 다른 글
| [연결리스트] 19 역순 연결 리스트 II(Reverse Linked List II) (0) | 2021.08.09 |
|---|---|
| [연결리스트] 18 홀짝 연결 리스트(Odd Even Linked List) (0) | 2021.08.09 |
| [연결리스트] 16 두 수의 덧셈(Reverse Linked List) (0) | 2021.08.09 |
| [연결리스트] 15 역순 연결 리스트(Reverse Linked List) (0) | 2021.08.09 |
| [연결리스트] 14 두 정렬 리스트의 병합(Merge Two Sorted Lists) (0) | 2021.08.09 |