728x90
LeetCode-24
swap-nodes-in-pairs_2 : 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
note : only nodes themselves may be changed.
MyAnswer
:::python
# 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]:
root = prev = ListNode(None)
prev.next = head
while head and head.next:
b = head.next
head.next = b.next
b.next = head
prev.next = b
head = head.next
prev = prev.next.next
return root.next
Result : 32ms Memory: 13.9mb
๋ฐ์ํ
'๐ข One step' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[leetcode-20] Valid Parenthese (0) | 2023.03.29 |
---|---|
[leetcode 92] Reverse Linked List II (0) | 2023.03.26 |
[leetcode 24] Swap Nodes in Pairs (0) | 2023.03.20 |
[leetcode-2] Add Two Numbers (0) | 2023.03.17 |
[leetcode-206] Reverse Linked List (0) | 2023.03.15 |