본문 바로가기
Algorithm/LeetCode

LeetCode - Swap Nodes in Pairs

by HaningYa 2020. 9. 3.
728x90

 

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


문제

Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list's nodes, only nodes itself may be changed.

 

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.


val 만 바꾼거

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public var val: Int
 *     public var next: ListNode?
 *     public init() { self.val = 0; self.next = nil; }
 *     public init(_ val: Int) { self.val = val; self.next = nil; }
 *     public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
 * }
 */
class Solution {
    func swapPairs(_ head: ListNode?) -> ListNode? {
        helper(head)
        return head
    }
    func helper(_ node : ListNode?) {
        if node == nil || node?.next == nil{
            return
        }
        let tmp = node!.val
        node!.val = node!.next!.val
        node!.next!.val = tmp
        
        helper(node!.next!.next)
    }
}

val 바꾸지말라해서 node 바꾼거

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public var val: Int
 *     public var next: ListNode?
 *     public init() { self.val = 0; self.next = nil; }
 *     public init(_ val: Int) { self.val = val; self.next = nil; }
 *     public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
 * }
 */
class Solution {
    func swapPairs(_ head: ListNode?) -> ListNode? {
        guard let headNode = head, headNode.next != nil else{
            return head
        }
        let secondNode = headNode.next
        let thirdNode = secondNode?.next
        
        secondNode?.next = headNode
        headNode.next = swapPairs(thirdNode)
        
        return secondNode
    }
}
728x90

댓글