본문 바로가기
알고리즘/leetcode

1721. Swapping Nodes in a Linked List - python

by 1.5볼트 2023. 5. 16.
728x90

https://leetcode.com/problems/swapping-nodes-in-a-linked-list/

 

Swapping Nodes in a Linked List - LeetCode

Can you solve this real interview question? Swapping Nodes in a Linked List - You are given the head of a linked list, and an integer k. Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from t

leetcode.com

 

링크드 리스트 

앞에서 k 번 원소와 뒤에서 k 번 원소의 자리를 바꾼다

링크드 리스트를 순회 하면서 모든 원소를 리스트에 넣어놓고 뒤에서부터 새로운 링크드 리스트를 생성한다 만들때 앞 위k 번째 원소의 자리를 바꾼다  

# 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: Optional[ListNode], k: int) -> Optional[ListNode]:
        d=[]
        while True:
            if head==None:
                break
            d.append(head.val)
            head=head.next
        l=len(d)
        if k==1 or  k==l:
            h=ListNode(d[0])
        else:
            h=ListNode(d[-1])
        for n in range(2,len(d)+1):
            if n==k:
                h=ListNode(d[k-1],h)
            elif l-n+1==k:
                h=ListNode(d[-k],h)
            else:
                h=ListNode(d[-n],h)
        return h

 

'알고리즘 > leetcode' 카테고리의 다른 글

347. Top K Frequent Elements  (0) 2023.05.25
24. Swap Nodes in Pairs - python  (0) 2023.05.19
59. Spiral Matrix II - python  (0) 2023.05.10
54. Spiral Matrix - python  (0) 2023.05.09
1572. Matrix Diagonal Sum - python  (0) 2023.05.08

댓글