연결 리스트를 입력받아 페어 단위로 스왑하라
입력 :
1->2->3->4
출력 :
2->1->4->3
from typing import List
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def printLinkedList(head: ListNode):
while head:
print(head.val)
head = head.next
node_4 = ListNode(4)
node_3 = ListNode(3, node_4)
node_2 = ListNode(2, node_3)
node_1 = ListNode(1, node_2)
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
cnt = 0
cur = head
nxt = head.next
while nxt:
if cnt == 0:
cur.val, nxt.val = nxt.val, cur.val
cnt += 1
else:
cnt = 0
cur = nxt
nxt = nxt.next
return head
solution = Solution()
printLinkedList(solution.swapPairs(node_1))
2 1 4 3
Accepted 32 ms 14.1 MB python3
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 = Solution()
printLinkedList(solution.swapPairs(node_1))
2 1 4 3
Accepted 32 ms 14.3 MB python3
같은 방법을 간단하게 구현함...
class Solution:
def swapPairs(self, head: ListNode) -> 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
solution = Solution()
printLinkedList(solution.swapPairs(node_1))
2 1 4 3
Accepted 28 ms 14.2 MB python3
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
solution = Solution()
printLinkedList(solution.swapPairs(node_1))
2 1 4 3
Accepted 28 ms 14.1 MB python3