-
2021-01-30] Swapping Nodes in a Linked ListIT/자기계발 ( Leetcode ) 2021. 1. 31. 16:23반응형
오늘의 문제:leetcode.com/problems/swapping-nodes-in-a-linked-list/
Swapping Nodes in a Linked List - 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
Daily Challenge는 어려워서.. 하고 Medium 문제중 하나를 선택하여 풀어보았다.
해당 예시를 보며 생각해보자.
입력값으론 Linked list 와 int가 주어지는데, ListNode의 앞에서 k 번째 값과 끝에서 k 번째 값을 스왑하는 문제이다.
예시 1번처럼 k가 2라면 ListNode의 값 2,4가 각 양끝의 2번째 값이고, 이를 스왑하여 값을 전달해주면 된다.
필자는 ListNode를 풀때는 배열로 치환 후 값을 변경하고 다시 ListNode 형태를 만드는 것을 좋아한다.
바로 문제풀이를 보면 이해할 수 있을 것 같다.
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def swapNodes(self, head: ListNode, k: int) -> ListNode: alist=[] # List로 치환할 변수 선언 while head!= None: alist.append(head.val) head=head.next N=len(alist) # list의 길이를 구하고 bindex=N-k # swap할 index값을 구하여 findex=k-1 alist[findex],alist[bindex] = alist[bindex],alist[findex] # list값을 치환 ans=None for i in alist[::-1]: # alist[::-1] 이 문법은 배열의 역순 출력으로 ListNode를 만들때 역순으로 만드는게 좋다. ans=ListNode(i,ans) # list를 ListNode 형태로 변경 return ans
반응형'IT > 자기계발 ( Leetcode )' 카테고리의 다른 글
2021-02-01] Number of 1 Bits (0) 2021.02.01 2021-01-31] Next PermutationSolution (0) 2021.02.01 2021-01-29] Vertical Order Traversal of a Binary Tree (0) 2021.01.29 2021-01-28] Smallest String With A Given Numeric Value (0) 2021.01.29 2021-01-27] Concatenation of Consecutive Binary Numbers (0) 2021.01.27