728x90
문제
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
'Algorithm > LeetCode' 카테고리의 다른 글
LeetCode - Search in Binary Search Tree (0) | 2020.09.10 |
---|---|
LeetCode - Reverse Linked List 🤦🏻 (0) | 2020.09.09 |
LeetCode - Reverse String (0) | 2020.09.03 |
LeetCode - Largest Time for Given Digits (0) | 2020.09.01 |
LeetCode - Running Sum of 1d Array (0) | 2020.08.30 |
댓글